首页 > 解决方案 > PHP 在特定的 html div 上使用 str_replace

问题描述

我们希望在标点符号中添加一些细线间距,以改善网页排版的外观。使用 str_replace添加细线间距以更改(what)( what )似乎非常简单,多次覆盖四个主要标点符号。

str_replace("(", "( ", $content);
str_replace(")", " )", $content);
str_replace("?", " ?", $content);
str_replace("!", " !", $content);

但是我们需要将替换过程限制在主 div 中的内容,<div id="main">bla (bla) bla</div>因为目标标点符号( ? ! )也被该页面上的 CSS、JS 等使用。

在应用空间插入之前,页面将被缩小,因此注释、换行符等将被删除,而不是问题。

有没有办法只针对内容字符串的一部分?

第二个问题是如何避免?在链接 url 中定位?基本上试图忽略<a href=url'>主 div 中的项目。

这个问题不是另一个询问提取信息的问题的重复。这是关于修改网页中的单个字母数字字符。

标签: phppreg-replacestr-replace

解决方案


您需要做的是将文档加载到DOMDocument中,然后选择元素中的所有相关元素<div id="main">并替换其中的文本。

像这样的东西

$find = ['(', ')', '?', '!']; // characters to find
$replace = ['(&#8202;', '&#8202;)', '&#8202;?', '&#8202;!']; // replacements

// create a "text-contains" selector for all the characters
$selector = implode(' or ', array_map(function($char) {
    return sprintf('contains(text(), "%s")', $char);
}, $find));

// create an XPath query to get the text nodes
$query = sprintf('//div[@id="main"]//*[%s]/text()', $selector);

$doc = new DOMDocument();
$doc->loadHTML($content);

$xpath = new DOMXPath($doc);
$elements = $xpath->query($query);

foreach ($elements as $element) {
    // You need to decode the entities when working directly with text nodes
    $element->nodeValue = html_entity_decode(str_replace($find, $replace, $element->nodeValue));
}

$newContent = $doc->saveHTML();

演示 ~ https://3v4l.org/Q0fsn

请参阅这篇关于该html_entity_decode()警告的帖子〜PHP中的DOM:解码实体和设置nodeValue


推荐阅读