Home >Backend Development >PHP Tutorial >How to Convert URLs in HTML Text to Links without Affecting URLs within Tags?
Your predicament involves finding a way to convert only text URLs into clickable links within HTML content. However, currently, the pattern you're using unintentionally converts URLs within tags as well.
To address this issue, we'll employ DOM (Document Object Model) and XPath. Specifically, XPath allows us to traverse the HTML document and select specific elements based on precise criteria. In this case, we need to identify text nodes that contain URLs and are not descendants of anchor () elements.
The following XPath query can effectively achieve this:
/html/body//text()[ not(ancestor::a) and ( contains(., "http://") or contains(., "https://") or contains(., "ftp://") ) ]
This query considers only text nodes that do not belong to anchors and contain at least one of the supported URL protocols.
Once we have the relevant text nodes, we can use PHP's PREG_REPLACE function to modify their content. Here's how we can replace the text with corresponding anchor tags:
foreach ($texts as $text) { $fragment = $dom->createDocumentFragment(); $fragment->appendXML( preg_replace( "~((?:http|https|ftp)://(?:\S*?\.\S*?))(?=\s|\;|\)|\]|\[|\{|\}|,|\"|'|:|<|$|\.\s)~i", '<a href=""></a>', $text->data ) ); $text->parentNode->replaceChild($fragment, $text); }
This code creates document fragments, modifies the text in each fragment using the PREG_REPLACE pattern, and then replaces the original text nodes with the modified fragments.
By following this approach, you can effectively convert text URLs into clickable links while excluding URLs within tags, providing you with the desired functionality.
The above is the detailed content of How to Convert URLs in HTML Text to Links without Affecting URLs within Tags?. For more information, please follow other related articles on the PHP Chinese website!