在使用php的domdocument和domxpath对html文档进行处理时,一个常见的需求是查找文本节点中的特定短语,并将其包裹在新的html元素中(例如,<span>标签)。开发者通常会使用preg_match_all结合preg_offset_capture来获取所有匹配项及其在文本中的偏移量,然后利用domtext::splittext()方法来分割文本节点,插入新的元素。
然而,当一个文本节点中存在多个匹配项时,直接按照从前往后的顺序进行修改会导致一个棘手的问题:在处理完第一个匹配项并修改了DOM结构后,原文本节点的长度和内部偏移量会发生变化。这使得后续匹配项的原始偏移量变得无效,从而导致DOMText::splitText()方法在尝试分割一个已经不存在或结构已改变的节点时,返回false,进而引发“Call to a member function splitText() on bool”的致命错误。
原始代码示例中,foreach ($matches as $group)的迭代方式也存在问题,它会重复处理匹配项,加剧了错误。
解决此问题的关键在于两点:
下面是经过优化和修正的PHP函数,它展示了如何正确地实现这一逻辑:
立即学习“PHP免费学习笔记(深入)”;
<?php /** * 自动将特定短语包裹在带有品牌样式的<span>标签中。 * * @param string $content 待处理的HTML内容。 * @return string 处理后的HTML内容。 */ function ccjm_branding_filter(string $content): string { // 仅在非管理后台且非AJAX请求时处理,并确保内容不为空 if (! (is_admin() && ! wp_doing_ajax()) && $content) { $DOM = new DOMDocument(); // 启用内部错误处理以抑制HTML5警告 libxml_use_internal_errors(true); // 加载HTML内容,确保UTF-8编码并添加<html>包装器以供解析 // LIBXML_HTML_NOIMPLIED 和 LIBXML_HTML_NODEFDTD 用于防止DOMDocument自动添加不必要的HTML/BODY标签 $DOM->loadHTML("<?xml encoding='utf-8' ?><html>{$content}</html>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); // 清除加载HTML时产生的错误 libxml_clear_errors(); // 初始化XPath处理器 $XPath = new DOMXPath($DOM); // 检索所有文本节点,排除<script>标签内的文本 $textNodes = $XPath->query("//text()[not(parent::script)]"); foreach ($textNodes as $node) { // 查找所有匹配的短语,并捕获其偏移量 // 正则表达式用于匹配 "C.C. Johnson & Malhotra, P.C." 或 "CCJM" 等变体 preg_match_all("/(C\.? ?C\.?(?:JM| Johnson (?:&|&|&|and) Malhotra)(?: Engineers, LTD\.?|, P\.?C\.?)?)/i", $node->textContent, $matches, PREG_OFFSET_CAPTURE); // 确保有匹配项,并且正确地获取匹配结果 if (!empty($matches[0])) { // 关键步骤:将匹配项数组倒序排列 // 这样在修改DOM时,从文本末尾开始操作,不会影响到前面未处理的匹配项的偏移量 $reversedMatches = array_reverse($matches[0]); foreach ($reversedMatches as $match) { // 确定匹配项的起始偏移量和长度 $offset = $match[1]; $length = strlen($match[0]); /** * 隔离匹配的文本及其后的内容。 * $node->splitText($offset) 会将原节点在$offset处分成两部分, * $word 成为新的文本节点,包含从$offset开始的文本。 * 原$node则保留$offset之前的文本。 */ $word = $node->splitText($offset); // $word->splitText($length) 会将$word节点在$length处再次分割, // $after 成为新的文本节点,包含$word中从$length开始的文本。 // $word则保留$length之前的文本(即匹配的短语)。 $after = $word->splitText($length); // 创建新的<span>元素 $span = $DOM->createElement("span"); $span->setAttribute("class", "__brand"); // 设置品牌样式类 // 将匹配的文本节点($word)替换为新创建的<span>元素 $word->parentNode->replaceChild($span, $word); // 将匹配的文本节点($word)重新插入到<span>元素内部 $span->appendChild($word); // 注意:这里不需要 `break`,因为我们要处理所有匹配项 } } } // 保存修改后的HTML内容 // 通过迭代documentElement的childNodes并调用saveHTML,可以避免DOMDocument自动添加不必要的<html><body>标签 $content = implode(array_map([$DOM->documentElement->ownerDocument, "saveHTML"], iterator_to_array($DOM->documentElement->childNodes))); } return $content; } // 示例:将此过滤器应用于WordPress的输出(如果适用) // add_filter("ccjm_final_output", "ccjm_branding_filter"); ?>
示例输入内容:
<p>C.C. Johnson & Malhotra, P.C. (CCJM) was an integral member of a large Design Team for a 16.5-mile-long Public-Private Partnership (P3) Purple Line Project. The east-west light rail system extends from New Carrollton in PG County, MD to Bethesda in MO County, MD with 21 stations and one short tunnel. CCJM was Engineer of Record (EOR) for the design of eight (8) Bridges and design reviews for 35 transit/highway bridges and over 100 retaining walls of different lengths/types adjacent to bridges and in areas of cut/fill. CCJM designed utility structures for 42,000 LF of relocated water mains and 19,000 LF of relocated sewer mains meeting Washington Suburban Sanitary Commission (WSSC), Md Dept of Transportation (MDOT) MTA, and Local Standards.</p>
经过ccjm_branding_filter函数处理后的输出:
<p><span class="__brand">C.C. Johnson & Malhotra, P.C.</span> (<span class="__brand">CCJM</span>) was an integral member of a large Design Team for a 16.5-mile-long Public-Private Partnership (P3) Purple Line Project. The east-west light rail system extends from New Carrollton in PG County, MD to Bethesda in MO County, MD with 21 stations and one short tunnel. <span class="__brand">CCJM</span> was Engineer of Record (EOR) for the design of eight (8) Bridges and design reviews for 35 transit/highway bridges and over 100 retaining walls of different lengths/types adjacent to bridges and in areas of cut/fill. <span class="__brand">CCJM</span> designed utility structures for 42,000 LF of relocated water mains and 19,000 LF of relocated sewer mains meeting Washington Suburban Sanitary Commission (WSSC), Md Dept of Transportation (MDOT) MTA, and Local Standards.</p>
可以看到,所有匹配的短语,无论是“C.C. Johnson & Malhotra, P.C.”还是“CCJM”,都被正确地包裹在了<span class="__brand">标签中,且没有出现任何错误。
通过采纳倒序迭代的策略,开发者可以有效规避在PHP DOMDocument中进行多次文本节点修改时遇到的常见错误,实现更健壮和可靠的HTML内容处理功能。
以上就是PHP DOMDocument与XPath:正确处理文本节点多重修改的策略的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 //m.sbmmt.com/ All Rights Reserved | php.cn | 湘ICP备2023035733号