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
Release: 2024-12-14 12:59:14
Original
159 people have browsed it

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

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

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

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template