为了账号安全,请及时绑定邮箱和手机立即绑定

PHP 在特定的 html div 上使用 str_replace

PHP 在特定的 html div 上使用 str_replace

PHP
侃侃无极 2023-03-11 13:51:16
我们希望在标点符号中添加细线间距,以改善网页排版的外观。使用 str_replace添加细线间距以更改(what)为(&#8202;what&#8202;)似乎非常简单,多次覆盖四个主要标点符号。str_replace("(", "(&#8202;", $content);str_replace(")", "&#8202;)", $content);str_replace("?", "&#8202;?", $content);str_replace("!", "&#8202;!", $content);但是我们需要将替换过程限制为仅主 div 中的内容,<div id="main">bla (bla) bla</div>因为目标标点符号( ? ! )也被该页面上的 CSS、JS 等使用。在应用空格插入之前,页面将被缩小,因此评论、换行符等将被删除,而不是一个问题。有没有办法只定位内容字符串的一部分?第二个问题是如何避免?在链接 url 中定位?基本上试图忽略<a href=url'>主 div 中的项目。这个问题不是另一个询问有关提取信息的问题的重复。这个是关于修改网页中的单个字母数字字符。
查看完整描述

1 回答

?
一只斗牛犬

TA贡献1784条经验 获得超2个赞

您需要做的是将文档加载到 中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();




查看完整回答
反对 回复 2023-03-11
  • 1 回答
  • 0 关注
  • 66 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信