Home >Backend Development >PHP Tutorial >How Can I Extract URLs from Text Using PHP Regular Expressions?

How Can I Extract URLs from Text Using PHP Regular Expressions?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 18:49:11287browse

How Can I Extract URLs from Text Using PHP Regular Expressions?

Extracting URLs from Text in PHP

Problem:

How can URLs be extracted from a given text string in PHP using regular expressions?

Solution:

The wp-includes/formatting.php file in the latest WordPress version provides a complex function called make_clickable that can be useful for this task. However, a more straightforward approach involves using a regular expression:

preg_match_all('#\bhttps?://[^\s()<>]+(?:(\([\w\d]+\))|([^[:punct:]\s]|/))#', $string, $match);

This regex matches URLs with the following characteristics:

  • Any valid URL starting with "http" or "https"
  • Optional port numbers enclosed in parentheses
  • No whitespaces, parentheses, angle brackets, or quotes allowed with optional trailing characters like forward slashes

It's important to note that some malformed URLs may not be removed by this regex, as in the example of "http://google:ha.ckers.org".

Additional Resources:

  • [How to mimic StackOverflow Auto-Link Behavior](insert link here)

The above is the detailed content of How Can I Extract URLs from Text Using PHP Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn