Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - preg_replace items in brackets with array items

I have an array:

array('id' => 'really')

I have a string:

$string = 'This should be {id} simple.';

I want to end up with:

This should be really simple.

I have a regular expression that will work with the {id} aspect, but I am having a hard time doing what I want.

/{([a-zA-Z\_\-]*?)}/i

{id} could be anything, {foo} or {bar} or anything that matches my regular expression.

I am sure that there is a simple solution that is escaping me at the moment.

Thanks,

Justin

like image 374
manumoomoo Avatar asked Jan 21 '23 21:01

manumoomoo


1 Answers

str_replace is faster then preg_replace, try this:

$arr = array('a' => 'a', 'b' => 'b');
$str = "{a} {b} {c}";
$values = array_values($arr);
$keys = array_keys($arr);

foreach ($keys as $k => $v) {
    $keys[$k] = '{'.$v.'}';
}

str_replace($keys, $values, $str);
like image 98
Stuck Avatar answered Jan 30 '23 18:01

Stuck