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

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

DDD
DDDOriginal
2024-12-14 12:59:14244browse

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

Efficient URL Extraction from Text in PHP

Query

Extract URLs from the following text using regular expressions, specifically preg_match():

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

Answer

To extract the URL from the provided string, leveraging regular expressions is a suitable approach. One effective regex pattern is:

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

This regex matches valid URLs by ensuring they begin with "http" or "https," contain a domain without spaces or special characters, and optionally include parameters or path information.

However, there is a limitation to consider. Malformed URLs, such as "http://google:ha.ckers.org," may not be fully filtered out by this pattern.

Alternatively, you can utilize the following WordPress function:

make_clickable($string);

This function is specifically designed for converting plain text into formatted strings with clickable URLs, providing a robust method for URL extraction.

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