Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to match "{number}"

I need to replace "{Z}" with "test(Z)" where Z is always an unsigned integer using PHP and regular expressions (unless there's 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 tricky part is that it needs to be done in the best manner possible concerning speed and memory use.

like image 226
Christian Avatar asked Jul 11 '10 23:07

Christian


2 Answers

The missing line is this:

$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 }

The $1 in the replacement string refers to the string captured by the first (and only) capturing group.

like image 91
Mark Byers Avatar answered Oct 22 '22 16:10

Mark Byers


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

In my experience, preg_replace is much faster than any method of doing replacements using str_replace or strtr.

like image 38
amphetamachine Avatar answered Oct 22 '22 17:10

amphetamachine