Linkifying URLs in PHP Strings
Problem:
Converting a string containing raw URLs into hyperlinks is a common task in web development. Consider the following string:
"Look on https://www.php.cn/link/f511186b08b671a4ad5a1deaae96e310".<br>
The goal is to transform it into:
Solution:
To linkify URLs in PHP, you can leverage regular expressions with preg_replace(). Here's an effective solution:
$string = "Look on https://www.php.cn/link/f511186b08b671a4ad5a1deaae96e310";<br>$string = preg_replace(</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">"~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~", "<a href=\"\0\">\0</a>", $string);
In this code, preg_replace() scans the string using the specified regular expression pattern. It identifies any substring that matches the pattern (a valid URL) and replaces it with an HTML anchor tag.
The pattern itself (~[[:alpha:]] ://1] [[:alnum:]/]~) matches any sequence of characters that starts with an alphabetic character, followed by a colon ("://") and a non-empty string that excludes angle brackets ("<" and ">"), spaces, and certain special characters. It ensures that only valid URLs are converted into hyperlinks.