regex - PHP replace : find and replace the same characters with different text -
how can find , replace same characters in string 2 different characters? i.e. first occurrence 1 character, , second 1 character, entire string in 1 go?
this i'm trying (so users need not type html in body): i've used preg_replace here, i'll willing use else.
$str = $str = '>>hello, code>> here text >>this more code>>'; $str = preg_replace('#[>>]+#','[code]',$str); echo $str; //output above //[code]hello, code[code] here text [code]this more code[code] //expected output //[code]hello, code[/code] here text [code]this more code[/code]
but problem here is, both >>
replaced [code]
. possible somehow replace first >>
[code]
, second >>
[/code]
entire output?
does php have in 1 go? how can done?
$str = '>>hello, code>> here text >>this more code>>'; echo preg_replace( "#>>([^>]+)>>#", "[code]$1[/code]", $str );
the above fail if following input:
>>here code >to break >stuff>>
to deal this, use negative lookahead:
#>>((?!>[^>]).+?)>>#
will pattern.
echo preg_replace( "#>>((?!>[^>]).+?)>>#", "[code]$1[/code]", $str );
Comments
Post a Comment