PHP - preg_replace elements in parentheses with array elements

I have an array:

array('id' => 'really') 

I have a line:

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

I want to end up with:

 This should be really simple. 

I have a regex that will work with the {id} aspect, but it's hard for me to do what I want.

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

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

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

Thanks,

Justin

+4
source share
3 answers

str_replace is faster than preg_replace, try the following:

 $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); 
+5
source

You can use the preg_replace modifier with e as:

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

Perfect link

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

Now why is your regular expression /{([a-zA-Z\_\-])*?}/i not working?

Did you put *? outside the copied parenthesis ( ) , as a result, you only capture the first character of the word found in { } .

Also note that you did not escape { and } , which are regular expression metacharacters used to specify the range quantifier {num} , {min,max} . But in your case there is no need to avoid them, because the regular expression mechanism can deduce from the context that { and } cannot be used as a range operator, since they do not have numbers in the required format inside them and, therefore, process them literally.

+4
source

preg_replace_callback has a callback function that makes such things possible.

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

If you do not want to use a global variable, create a class and use the array($object, 'method') feedback.

0
source

Source: https://habr.com/ru/post/1332298/


All Articles