Convert plain text URLs into HTML hyperlinks in PHP
You can use the preg_replace()
function in PHP to convert plain text URLs into HTML hyperlinks. Here is an example:
<?php
$text = "Visit our website at http://www.example.com for more information.";
$html = preg_replace("/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w\- .\/?%&=]*)?/", "<a href='$0'>$0</a>", $text);
echo $html;
?>
The regular expression used in the preg_replace()
function will match any URL that starts with "http" or "https" and is followed by any combination of letters, numbers, and special characters. The matched URL will then be replaced with an HTML hyperlink that uses the matched URL as the href
attribute value.
You can also add target and title attribute to the links using
<?php
$text = "Visit our website at http://www.example.com for more information.";
$html = preg_replace("/http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w\- .\/?%&=]*)?/", "<a href='$0' target='_blank' title='Link to $0'>$0</a>", $text);
echo $html;
?>
This will open the link in new tab and show the link on hover.