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

Popular posts from this blog

javascript - Jquery show_hide, what to add in order to make the page scroll to the bottom of the hidden field once button is clicked -

javascript - Highcharts multi-color line -

javascript - Enter key does not work in search box -