【问题标题】:How to replace a word only in a <p>-tag?如何仅替换 <p> 标记中的单词?
【发布时间】:2016-10-02 14:09:20
【问题描述】:

如何仅替换 &lt;p&gt;-Tag 中的单词,而不替换内容中的 &lt;h3&gt;&lt;p class="no-change"&gt;-Tag 中的单词?

我想改变这个:

    <p>My Text and an Old Word and more </p>

    <p>My Text and an New Word and more </p>

我试过了:

    function changer($content){

    $word = str_replace('Old Word', 'New Word', $content);
    $content = preg_replace('/<h3>(.*?)<\/h3>/im', $word, $content);  

    return $content; 

    }

    add_filter('the_content','changer');

但我得到了双重结果......

【问题讨论】:

标签: php regex string preg-replace str-replace


【解决方案1】:

你得到一个双倍的结果,因为:

$word    = str_replace( 'Old Word', 'New Word', $content );

$word 是完整的$content,其中Old Word 替换为New Word。然后在preg_replace 中替换为$word,这样找到的位将替换为完整的$content 减去已替换的Old Word

每次更新一种方法:

$html = '<p>My Text and an Old Word and more </p>
<p>My Text and an Old2 Word and more </p>
<p>My Text and an Old3 Word and more </p>
<h3>My Text and an Old Word and more </h3>';
$html = preg_replace_callback('~<p>(.*?)</p>~', function ($p_content) {
    return str_replace('Old Word', 'New Word', $p_content[1]);
}, $html);
echo $html;

您还可以使用解析器并遍历所有 p 元素以查看它们是否包含 Old Word

演示:https://eval.in/582129

【讨论】:

  • 太棒了!非常感谢您提供此解决方案!效果很好! (当我有 15 个声望时,我会投票赞成你的答案。)
猜你喜欢
  • 2017-11-03
  • 1970-01-01
  • 2013-10-19
  • 1970-01-01
  • 2017-01-21
  • 1970-01-01
  • 2020-01-06
  • 1970-01-01
  • 2012-12-23
相关资源
最近更新 更多