Home >Backend Development >PHP Tutorial >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:
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:
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!