【问题标题】:How to replace certain div with preg_replace?如何用 preg_replace 替换某些 div?
【发布时间】:2019-10-04 10:41:01
【问题描述】:

我有这段代码 HTML:

<div class="wrap">
<div class="wp-checkbox" data-value="zf">content</div>
<div class="wp-checkbox" data-value="tdp">content</div>
</div>

我想替换这些 div 的内容,但每个都不同。

我尝试通过代码来实现:

$pattern = '/=\"zf\">.*<\/div>/';
$pattern2 = '/=\"tdp\">.*<\/div>/';
$html = preg_replace( $pattern, '="zf">new content of div</div>', $html );
$html = preg_replace( $pattern2, '="tdp">new content of another div</div>', $html );

但是这段代码有一个问题 - 它替换了我所有的 div,我得到了这个:

<div class="wrap">
<div class="wp-checkbox" data-value="zf">new content of div</div>
</div>

如何一一更改这些 div?如何在模式中显示我只想更改直到第一次关闭&lt;/div&gt;(而不是最后一个)?

我想得到这个结果:

<div class="wrap">
<div class="wp-checkbox" data-value="zf">new content of div</div>
<div class="wp-checkbox" data-value="tdp">new content of div</div>
</div>

提前感谢您的帮助。

【问题讨论】:

标签: php preg-replace


【解决方案1】:

您真的不应该尝试使用正则表达式来解析 HTML。相反,使用 DOMDocument 类来处理 HTML:

$doc = new DOMDocument();
$doc->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
$div = $xpath->query('//div[@data-value="zf"]')[0];
$div->nodeValue = "new content of div";
$div = $xpath->query('//div[@data-value="tdp"]')[0];
$div->nodeValue = "new content of another div";
echo $doc->saveHTML();

输出:

<div class="wrap">
<div class="wp-checkbox" data-value="zf">new content of div</div>
<div class="wp-checkbox" data-value="tdp">new content of another div</div>
</div>

Demo on 3v4l.org

如果您必须使用正则表达式,您只需通过在.* 之后添加? 来纠正您的模式以使其不贪婪:

$pattern = '/=\"zf\">.*?<\/div>/';
$pattern2 = '/=\"tdp\">.*?<\/div>/';
$html = preg_replace( $pattern, '="zf">new content of div</div>', $html );
$html = preg_replace( $pattern2, '="tdp">new content of another div</div>', $html );

输出:

<div class="wrap">
<div class="wp-checkbox" data-value="zf">new content of div</div>
<div class="wp-checkbox" data-value="tdp">new content of another div</div>
</div>

Demo on 3v4l.org

【讨论】:

  • 谢谢你的回答,即使我回答你的时候也不是很好。不幸的是,代码是由插件生成的,我只能通过函数来​​更改它。所以我不知道如何在函数中使用它。
  • @kibus90 查看我的编辑。我已经为您的正则表达式提供了一个修复程序。
猜你喜欢
  • 2013-02-24
  • 1970-01-01
  • 2011-01-24
  • 2015-08-09
  • 1970-01-01
  • 2012-07-01
  • 2017-04-01
  • 2014-06-10
  • 2011-02-19
相关资源
最近更新 更多