How to use PHP preg_replace regular expression to find and replace text
Posted
by
Roger
on Stack Overflow
See other posts from Stack Overflow
or by Roger
Published on 2011-01-13T19:36:56Z
Indexed on
2011/01/13
19:54 UTC
Read the original article
Hit count: 261
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 :-)
© Stack Overflow or respective owner