php - 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 中的项目。
这个问题不是另一个询问提取信息的问题的重复。这是关于修改网页中的单个字母数字字符。
解决方案
您需要做的是将文档加载到DOMDocument
中,然后选择元素中的所有相关元素<div id="main">
并替换其中的文本。
像这样的东西
$find = ['(', ')', '?', '!']; // characters to find
$replace = ['( ', ' )', ' ?', ' !']; // 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();
请参阅这篇关于该html_entity_decode()
警告的帖子〜PHP中的DOM:解码实体和设置nodeValue
推荐阅读
- xml - 内部子集 DTD 引用外部 DTD
- python - 使用装饰器将函数添加到字典
- google-drive-api - Gdrive API:用户对此文件没有足够的权限
- javascript - 在node.js中使用cherio(两次)导出网络链接
- r - FOR循环计算R中日期的差异
- pandas - 将函数/方法转换为字符串?
- python-3.x - Sphinx 和 TypedDict
- biztalk - BizTalk 应用程序消耗 api 更改为 TSL 1.0 到 1.2。BizTalk 端的必需更改是什么?
- angular - Angular 表达式中的整数在 Angular 10 中不起作用
- javascript - Fetch() - 如何使用重定向显示位置页面:follow