Home > Backend Development > PHP Tutorial > How Can I Efficiently Extract URLs from Text in PHP?

How Can I Efficiently Extract URLs from Text in PHP?

Patricia Arquette
Release: 2024-12-21 14:46:14
Original
339 people have browsed it

How Can I Efficiently Extract URLs from Text in PHP?

Extracting URLs from Text in PHP: Effective Techniques

When working with text data in PHP, extracting URLs is a common task. With the help of regular expressions, you can efficiently identify and parse URL patterns from text strings.

Regular Expression Approach

One method for URL extraction is using regular expressions, particularly preg_match(). Consider the following example:

$string = "this is my friend's website http://example.com I think it is cool";

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

This regular expression will match all valid URLs in the text string, including their "http://" and "https://" prefixes.

WordPress Function

WordPress provides a helpful function called make_clickable(), which takes plain text as input and generates formatted output. This function is commonly used to transform text into clickable HTML links, including URLs.

To extract URLs using make_clickable(), you can download the latest WordPress version and refer to the wp-includes/formatting.php file. This function is suitable for handling complex text formats and includes various conditions to avoid extracting malformed URLs.

Additional Resources

Beyond these techniques, you may also find the following resources beneficial:

  • [How to mimic StackOverflow Auto-Link Behavior](https://wordpress.stackexchange.com/questions/15691/how-to-mimic-stackoverflow-auto-link-behavior)

The above is the detailed content of How Can I Efficiently Extract URLs from Text in PHP?. 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