如何仅在<p> -tag中替换单词?

时间:2016-06-02 17:33:03

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

如何仅在<p> - 代码中替换字词,而不是在内容中的<h3><p class="no-change"> - 代码中替换字词?

我想改变这个:

    <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');

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

1 个答案:

答案 0 :(得分:2)

你得到双重结果,因为:

png

$word = str_replace( 'Old Word', 'New Word', $content ); 是完整的$word$content替换为Old Word。然后,您使用New Word中的$word进行替换,以便将已找到的位替换为已经替换的preg_replace更少的$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

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