The regular expression matches {{number} "

I need to replace "{Z}" with "test (Z)", where Z is always an unsigned integer using PHP and regular expressions (unless there is a faster way?).

$code='{45} == {2}->val() - {5}->val()'; // apply regex to $code echo $code; // writes: test(45) == test(2)->val() - test(5)->val() 

The hard part is that it needs to be done in the best possible way in terms of speed and memory usage.

+4
source share
2 answers

Invalid line:

 $code = preg_replace('/{([0-9]+)}/', 'test($1)', $code); 

How it works:

  {match a literal {
 (start a capturing group
 [0-9] + one or more digits in 0-9
 ) end the capturing group
 } match a literal}

$ 1 in the replacement line refers to the line captured by the first (and only) capture group.

+8
source
 $code = preg_replace('/\{(\d+)\}/', 'test($1)', $code); 

In my experience, preg_replace much faster than any method of taking notes using str_replace or strtr .

+5
source

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


All Articles