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
The regular expression breaks down as follows:
https?://matcheshttporhttpsfollowed 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
This will open the link in a new tab and display the link text on hover.