Converting Plain Text URLs into HTML Hyperlinks in PHP
To convert plain text URLs into HTML anchor links in PHP, you can utilize the preg_replace() function with an appropriate regular expression.
A comprehensive solution that captures various types of URLs is:
$url = '@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@'; $string = preg_replace($url, '<a href="http://" target="_blank" title="<pre class="brush:php;toolbar:false">$url = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/'; $string= preg_replace($url, '<a href="<pre class="brush:php;toolbar:false">$email = '<a href="mailto:[email protected]">[email protected]</a>'; $string = $email;
This expression targets all URL types and appends an href attribute with the captured link, ensuring compatibility across different setups.
Alternatively, if you want to match only HTTP/S URLs, you can use:
For situations where URLs are displayed incorrectly, you can implement this simple solution:
Remember that depending on the server configuration and specific requirements, different scripts might yield different results. The provided solutions aim to accommodate various scenarios and offer a starting point for customization.
The above is the detailed content of How to Convert Plain Text URLs into HTML Hyperlinks in PHP?. For more information, please follow other related articles on the PHP Chinese website!