How to use PHP preg_replace regular expression to find and replace text
- by Roger
I wrote this PHP code to make some substitutions:
function cambio($txt){
$from=array(
'/\+\>([^\+\>]+)\<\+/', //finds +>text<+
'/\%([^\%]+)\%/', //finds %text%
);
$to=array(
'<span class="P">\1</span>',
'<span>\1</span>',
);
return preg_replace($from,$to,$txt);
}
echo cambio('The fruit I most like is: +> %apple% %banna% %orange% <+.');
Resulting into this:
The fruit I most like is: <span class="P"> <span>apple</span> <span>banna</span> <span>orange</span> </span>.
however I needed to identify the fruit's span tags, like this:
The fruit I most like is: <span class="P"> <span class="a">apple</span> <span class="b">banna</span> <span class="c">coco</span> </span>.
I'd buy a fruit to whom discover a regular expression to accomplish this :-)