Home >Backend Development >PHP Tutorial >How to Detect and Convert URLs to HTML Links in PHP?
Detect and Convert URLs to HTML Links in Text
In various online applications, converting URLs mentioned in text to clickable links is a common requirement. Let's explore how to accomplish this in PHP.
Requirements
Solution
Regular Expression-Based Approach
Let's create a regular expression that matches valid URLs and their constituent parts:
$rexProtocol = '(https?://)?'; $rexDomain = '((?:[-a-zA-Z0-9]{1,63}\.)+[-a-zA-Z0-9]{2,63}|(?:[0-9]{1,3}\.){3}[0-9]{1,3})'; $rexPort = '(:[0-9]{1,5})?'; $rexPath = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?'; $rexQuery = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; $rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?'; $rex = "&\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&";
Implementation
We can use preg_match_all() to find all URL matches in the text:
preg_match_all($rex, htmlspecialchars($text), $matches, PREG_OFFSET_CAPTURE);
Convert to HTML Links
We'll loop through the matches and create the appropriate HTML links:
foreach ($matches[0] as $match) { $url = $match[0]; $domain = $matches[2][0]; $path = $matches[4][0]; $completeUrl = $matches[1][0] ? $url : "http://$url"; $htmlLink = "<a href='$completeUrl'>$domain$path</a>"; $text = str_replace($url, $htmlLink, $text); }
This approach handles most URL formats efficiently while maintaining security against XSS attacks.
The above is the detailed content of How to Detect and Convert URLs to HTML Links in PHP?. For more information, please follow other related articles on the PHP Chinese website!