
在网页内容处理中,我们经常需要识别并修改特定的文本片段,例如将所有出现的品牌名称用<span>标签包裹起来。PHP的DOMDocument和XPath提供了强大的能力来实现这一点。然而,当一个文本节点中存在多个匹配项,并且我们尝试使用DOMText::splitText()方法逐一修改它们时,一个常见的陷阱是,第一次修改会改变文本节点的内部结构,从而使得后续匹配项的偏移量失效,导致splitText()调用失败并抛出Fatal error: Uncaught Error: Call to a member function splitText() on bool错误。
具体来说,DOMText::splitText(offset)方法会在指定偏移量处将当前文本节点一分为二,返回一个新的文本节点(从偏移量开始的部分)。如果我们在一个文本节点上连续进行多次splitText()操作,并且每次操作都基于原始文本的偏移量,那么在第一次splitText()之后,原始文本节点的长度和内容都已改变,后续的偏移量将不再准确,甚至可能指向一个不再存在的文本部分,导致splitText()返回false,进而引发错误。
要解决此问题,我们需要采取两种关键策略:
以下是基于原始问题的代码,并应用上述解决方案后的修正版本。我们将专注于foreach ($text as $node)循环内部的修改逻辑。
立即学习“PHP免费学习笔记(深入)”;
/**
* Automatically wrap various forms of CCJM in a class for branding purposes
*
* @param string $content
* @return string
*/
function ccjm_branding_filter(string $content): string {
if (! (is_admin() && ! wp_doing_ajax()) && $content) {
$DOM = new DOMDocument();
/**
* Use internal errors to get around HTML5 warnings
*/
libxml_use_internal_errors(true);
/**
* Load in the content, with proper encoding and an `<html>` wrapper required for parsing
*/
$DOM->loadHTML("<?xml encoding='utf-8' ?><html>{$content}</html>", LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
/**
* Clear errors to get around HTML5 warnings
*/
libxml_clear_errors();
/**
* Initialize XPath
*/
$XPath = new DOMXPath($DOM);
/**
* Retrieve all text nodes, except those within scripts
*/
$text = $XPath->query("//text()[not(parent::script)]");
foreach ($text as $node) {
/**
* Find all matches, including offset
* PREG_OFFSET_CAPTURE 捕获匹配项的偏移量
*/
preg_match_all("/(C\.? ?C\.?(?:JM| Johnson (?:&|&|&|and) Malhotra)(?: Engineers, LTD\.?|, P\.?C\.?)?)/i", $node->textContent, $matches, PREG_OFFSET_CAPTURE);
/**
* 确保有匹配项才进行处理
* 逆序遍历匹配项,以避免DOM修改导致的偏移量失效问题
* $matches[0] 包含所有完整匹配的字符串及其偏移量
*/
$group = array_reverse($matches[0]); // 关键:逆序遍历 $matches[0]
foreach ($group as $match) {
/**
* Determine the offset and the length of the match
*/
$offset = $match[1];
$length = strlen($match[0]);
/**
* Isolate the match and what comes after it
* splitText(offset) 会将当前节点在 offset 处分割,
* 并返回从 offset 开始的新节点。
* 原节点会保留 offset 之前的部分。
*/
$word = $node->splitText($offset);
/**
* 再次调用 splitText,从 $word 节点的开头(即原匹配项的开头)
* 分割出匹配项本身。
* $after 节点将包含匹配项之后的部分。
*/
$after = $word->splitText($length);
/**
* Create the wrapping span
*/
$span = $DOM->createElement("span");
$span->setAttribute("class", "__brand");
/**
* Replace the word (匹配到的文本节点) with the span,
* and then re-insert the word within it
*/
$word->parentNode->replaceChild($span, $word);
$span->appendChild($word);
}
}
/**
* Save changes, remove unneeded tags
* 提取 body 内容,去除 html/body 包装
*/
$content = implode(array_map([$DOM->documentElement->ownerDocument, "saveHTML"], iterator_to_array($DOM->documentElement->childNodes)));
// 如果需要更精确地获取<body>内的内容,可以查询body节点
// $body = $XPath->query('//body')->item(0);
// if ($body) {
// $content = '';
// foreach ($body->childNodes as $child) {
// $content .= $DOM->saveHTML($child);
// }
// }
}
return $content;
}
// add_filter("ccjm_final_output", "ccjm_branding_filter"); // 如果是WordPress环境,则需要此行代码修改要点:
使用提供的示例内容:
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.
经过修正后的代码处理,输出结果将如下所示,所有匹配的短语都被正确地包裹在<span>标签中:
<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>
通过采用逆序遍历匹配项的策略,我们能够有效地规避PHP DOMDocument在处理单个文本节点内多个修改时所面临的偏移量失效问题,从而实现稳健且准确的文本内容转换。理解DOM操作的底层机制是编写高效且无错代码的关键。
以上就是解决PHP DOM操作中多次修改文本节点导致的splitText错误的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号