W3docs

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.

You can use the preg_replace() function in PHP to convert plain text URLs into HTML hyperlinks. Here is an example:

Example of using the preg_replace() function in PHP to convert plain text URLs into HTML hyperlinks

<?php
$text = "Visit our website at http://www.example.com for more information.";
$html = preg_replace("/https?:\/\/(?:[\w-]+\.)+[\w-]+(?:\/[\w\-./?%&=]*)?/", "<a href='$0'>$0</a>", $text);
echo $html;
?>

The regular expression breaks down as follows:

  • https?:// matches http or https followed by ://
  • (?:[\w-]+\.)+[\w-]+ matches the domain name and subdomains
  • (?:\/[\w\-./?%&=]*)? matches an optional path, query string, or parameters

The matched URL is then replaced with an HTML hyperlink using the captured URL as the href attribute value.

⚠️ Note: This regex may capture trailing punctuation (like periods or commas) at the end of sentences. For production use, consider a more robust URL parser or a regex that explicitly excludes trailing punctuation. Additionally, always escape user-generated content before rendering it as HTML to prevent XSS attacks.

You can also add target and title attributes to the links by modifying the replacement string:

Example of using the preg_replace() function in PHP to convert plain text URLs into HTML hyperlinks with target and title attributes

<?php
$text = "Visit our website at http://www.example.com for more information.";
$html = preg_replace("/https?:\/\/(?:[\w-]+\.)+[\w-]+(?:\/[\w\-./?%&=]*)?/", "<a href='$0' target='_blank' title='Link to $0'>$0</a>", $text);
echo $html;
?>

This will open the link in a new tab and display the link text on hover.