php - preg_replace all occurrences in string withing defined delimeters -
i trying replace occurrences of "a" "b" inside string. problem need replace letters inside brackets:
asd asd asd [asd asd asd] asd asd asd
for have code:
$what = '/(?<=\[)a(?=.*?\])/s'; $with = 'b'; $where = 'asd asd asd [asd asd asd] asd asd asd';
but replaces first "a", , getting result:
asd asd asd [bsd asd asd] asd asd asd
i realy need done 1 preg_replace call.
you cannot single preg_replace
call because lookbehind need "there opening square bracket somewhere before match" , impossible since lookbehind patterns must have fixed length.
why absolutely need in 1 call anyway? doable pretty preg_replace_callback
, match groups of content inside square brackets , use preg_replace
on match each time (or simple str_replace
if going replace "a" "b").
example:
$what = '/\[([^]]*)\]/'; $where = 'asd asd asd [asd asd asd] asd asd asd'; echo preg_replace_callback( $what, function($match) { return '['.str_replace('a', 'b', $match[1]).']'; }, $where);
Comments
Post a Comment