Sunday, 15 April 2012

php - Preg_replace all patterns in a string -



php - Preg_replace all patterns in a string -

i have str :

'test code {b}{x} implementing prototype {t} , using combinations of {u}{a} , {l/w}{f/k}.

i need replace each occurance of {*} it's corresponding code, resulting string be:

'test code <img src="../b.jpg"><img src="../x.jpg"> implementing prototype <img src="../t.jpg"> ,using combinations of <img src="../u.jpg"> <img src="../a.jpg"> , <img src="../lw.jpg"> <img src="../fk.jpg">.

i don't wish utilize str_replace , type out combinations because there literally thousands of them. $combinations = array("{b}", "{x}", "{w}{x},"{x/w}","{a/l}".."); etc

so i'm using preg_match_all find occurrences string.

function findmatches($start, $end, $str){ $matches = array(); $regex = "/$start([\/a-za-z0-9_]*)$end/"; preg_match_all($regex, $str, $matches); homecoming $matches[1]; }

which returns me,

array ( [0] => b [1] => x [2] => t [3] => u [4] => [5] => l/w [6] => f/k )

the problem don't need '/' between letters, suppose str_replace later.

my question how can preg_replace using array of matches , homecoming modified string instead of array?

i suggest using preg_replace_callback() accomplish this. can utilize str_replace() method replace forwards slash / in match callback function returns.

$text = <<<data test code {b}{x} implementing prototype {t} , using combinations of {u}{a} , {l/w}{f/k}. data; $text = preg_replace_callback('~{([^}]*)}~', function($m) { homecoming '<img src="../' . str_replace('/', '', $m[1]) . '.jpg">'; }, $text); echo $text;

working demo

php regex string

No comments:

Post a Comment