PHP str_replace with wild card?

I know how to use str_replace for simple tasks, for example ...

$Header = str_replace('<h2>Animals</h2>', '<h3>Animals</h3>', $Header);

But imagine an article stored in a database that includes the following headings:

<h3>Animals</h3>
<h3>Plants</h3>

And you want to change them to this:

<h3><span class="One">Animals</span></h3>
<h3><span class="One">Plants</span></h3>

Is there a way to turn a value between tags (e.g. Animals, Plants, Minerals, etc.) into a wild card, something like this:

$Title = str_replace('<h3>*</h3>', '<h3><span style="One">*</span></h3>', $Title);

Or should I ask: "What is the best way?" There seem to be ways to do this, but I would like to try to find a simple PHP solution before starting the fight against regular expressions.

+5
source share
1 answer

str_replace(), , , preg_replace() - .

<?php
$str = <<<EOD

<h3>Animals</h3>
<h3>Plants</h3>

EOD;

$str = preg_replace('/<h3>(.*?)<\/h3>/', '<h3><span class="One">$1</span></h3>', $str);

echo $str;
+10

All Articles