PHP 在特定 html div 上使用 str_replace

PHP using str_replace on a specific html div

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

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

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

在应用 space 插入之前,页面将被缩小,因此评论、换行符等将被删除,而不是一个问题。

有没有办法只定位内容字符串的一部分?

第二个问题是如何避免在 link url 内定位 ??基本上试图忽略主 div.

中的 <a href=url'> 中的项目

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

您需要做的是将您的文档加载到 DOMDocument,然后 select 您的 <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

看到这个 post 关于 html_entity_decode() 警告 ~ DOM in PHP: Decoded entities and setting nodeValue