Home  >  Article  >  Backend Development  >  How to Exclude HTML Tags from Text URL Detection and Replacement?

How to Exclude HTML Tags from Text URL Detection and Replacement?

Barbara Streisand
Barbara StreisandOriginal
2024-10-28 04:53:30197browse

How to Exclude HTML Tags from Text URL Detection and Replacement?

Exclude HTML Tags from Text URL Detection and Replacement

In your quest to convert plain text URLs into HTML anchor tags, excluding those within HTML tags, you have encountered a hurdle with your current regex. This article aims to provide a comprehensive solution to this challenge.

Your current regex approach effectively detects and replaces URLs in text, but it also mistakenly targets URLs within HTML tags. To rectify this, we must employ a more targeted approach.

Using XPath to Identify Eligible URLs

Instead of a broad text search, we can utilize XPath to precisely select text nodes containing URLs that are not descendants of anchor elements. This ensures that URLs within HTML tags are not affected.

$xPath = new DOMXPath($dom);
$texts = $xPath->query('/html/body//text()[not(ancestor::a) and (contains(., "http://") or contains(., "https://") or contains(., "ftp://"))]');

Replacing Text Nodes with Document Fragments

Rather than modifying the text nodes directly, we will use document fragments to replace the entire text node with the desired HTML. This non-standard technique streamlines the process.

foreach ($texts as $text) {
    $fragment = $dom->createDocumentFragment();
    $fragment->appendXML(
        preg_replace("~((?:http|https|ftp)://(?:\S*?\.\S*?))(?=\s|\;|\)|\]|\[|\{|\}|,|\&quot;|'|:|\<|$|\.\s)~i", '<a href=&quot;&quot;></a>', $text->data)
    );
    $text->parentNode->replaceChild($fragment, $text);
}

Output

This approach effectively converts eligible URLs in plain text into HTML anchor tags, while excluding those within HTML tags. The resulting HTML will reflect the desired conversions without any unwanted modifications.

The above is the detailed content of How to Exclude HTML Tags from Text URL Detection and Replacement?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn