Linking URLs in a String with PHP
Problem:
Given a string containing URLs, one needs to convert these URLs into clickable links. The original string may contain multiple URLs.
Solution:
PHP offers several approaches to linkify URLs in a string:
Using preg_replace()
This function can be employed as follows:
<code class="php">$string = "Look on http://www.google.com"; $string = preg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~", "<a href=\"\0\">\0</a>", $string);</code>
Using ereg_replace()
For PHP versions prior to 5.3, ereg_replace() provides an alternative:
<code class="php">$string = "Look on http://www.google.com"; $string = ereg_replace("~[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]~", "<a href=\"\0\">\0</a>", $string);</code>
Both methods effectively convert URLs in the string into clickable links.
The above is the detailed content of How do I turn URLs in a string into clickable links using PHP?. For more information, please follow other related articles on the PHP Chinese website!