manumoomoo
manumoomoo

Reputation: 2757

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

Upvotes: 4

Views: 3518

Answers (3)

Stuck
Stuck

Reputation: 12292

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);

Upvotes: 4

codaddict
codaddict

Reputation: 454920

You can use the preg_replace with e modifier as:

$string = preg_replace('/{([a-zA-Z\_\-]*?)}/ie','$arr["$1"]',$string);

Ideone Link

Using the e modifier you can have any PHP expression in the replacement part of preg_replace.

Now why did your regex /{([a-zA-Z\_\-])*?}/i not work?

You've put *? outside the capturing parenthesis ( ) as a result you capture only the first character of the word found in { }.

Also note that you've not escaped { and } which are regex meta-character used for specifying range quantifier {num}, {min,max}. But in your case there is no need to escape them because the regex engine can infer from the context that { and } cannot be used as range operator as they are not having numbers in required format inside them and hence treats them literally.

Upvotes: 4

RageZ
RageZ

Reputation: 27313

preg_replace_callback has a callback option which make that kind of things possible.

function replaceText($matches){
  global $data;
  return $data[$matches[1]];
}
preg_replace_callback(
        '/{([a-zA-Z\_\-])*?}/i',
        'replaceText',
        $content
);

If you don't want to use the global variable create an class and use the array($object, 'method') callback notation.

Upvotes: 1

Related Questions