1

How can I replace a word only in a <p>-Tag, and not in a <h3> or <p class="no-change">-Tag in the content?

I want to change this:

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

in

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

I tried this:

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

But I get a double result...

Tada
  • 33
  • 1
  • 6

1 Answers1

2

You get a double result because:

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

The $word is the full $content with Old Word replaced with New Word. You then replace with $word in the preg_replace so the found bit is replaced with the full $content less the Old Word which was already replaced.

Per update one approach:

$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;

You also could use a parser and iterate over all p elements to see if they contain Old Word.

Demo: https://eval.in/582129

chris85
  • 23,846
  • 7
  • 34
  • 51
  • Amazing! Thank you so much for this solution! That works great! (I up vote your answer when I have 15 reputations.) – Tada Jun 02 '16 at 18:16