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
Release: 2024-12-09 18:49:11
Original
321 people have browsed it

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);
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template