Home > Article > Backend Development > How to Highlight Search Results in HTML Without Breaking the Structure?
How to Exclude HTML Tags in preg_replace
The provided code attempts to highlight search results within a string using preg_replace. However, the presence of HTML tags in the string poses a challenge as the replacement operation inadvertently tags the tags themselves, breaking the HTML structure.
Solution: Employing a DOM-Based Approach
Regular expressions are not the ideal tool for parsing HTML. Instead, consider using the DOM (Document Object Model) and DOMXPath to navigate the XML structure of your string.
DOMXPath allows you to search for elements containing specific text, ignoring XML elements. This allows you to isolate the relevant text nodes and wrap them in the desired span tags.
Code Implementation
The following code demonstrates how to implement this approach:
$doc = new DOMDocument; $doc->loadXML($str); $xp = new DOMXPath($doc); // Search elements containing the search text $r = $xp->query('//*[contains(., "'.$search.'")]/*[FALSE = contains(., "'.$search.'")]/..', $anchor); // Process search results foreach($r as $i => $node) { // Extract search text nodes and create suitable nodes if necessary $range = new TextRange($xp->query('.//child::text()', $node)); $ranges = array(); while(FALSE !== $start = strpos($range, $search)) { $base = $range->split($start); $range = $base->split(strlen($search)); $ranges[] = $base; }; // Wrap matching text nodes foreach($ranges as $range) { foreach($range->getNodes() as $node) { $span = $doc->createElement('span'); $span->setAttribute('class', 'search_hightlight'); $node = $node->parentNode->replaceChild($span, $node); $span->appendChild($node); } } }
This code searches for elements containing the search text, ignoring any child elements that do not contain it. The search areas are represented as TextRange objects, allowing for the insertion of span tags around the matching text. The result is a modified XML string with highlighted search results, without breaking the HTML structure.
The above is the detailed content of How to Highlight Search Results in HTML Without Breaking the Structure?. For more information, please follow other related articles on the PHP Chinese website!