Elisa Elisa - 6 months ago 9
PHP Question

How to replace a word only in a <p>-tag?

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...

Answer

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

Comments