Page 1 of 1

[SOLVED] Problem with regex and backreference

Posted: Mon Dec 20, 2010 1:42 am
by dreamline
Hi All,
I'm trying to use the backreference \\1 or \${1} in a preg_replace, however I'm not able to get it right. Here's an example of what I want to accomplish:

Code: Select all

$mytest->data['TEST'] = 'This is a regular test';
$text = '[TEST] based on my findings';
$new_text = preg_replace('/\[([^0-9](?:[A-Z0-9\-_]+))\]/', (isset($mytest->data['\\1']) ? $mytest->data['\\1'] : '')  , $text);
print_r($new_text);
Basically what I'm trying to do is check if $mytest->data['TEST'] has been set. If so it should print it's value, if not then it prints an empty string. However it always prints an empty string.

Hope some one can help me out. :)

Re: [SOLVED] Problem with regex and backreference

Posted: Mon Dec 20, 2010 5:42 am
by dreamline
Figured it out. Forgot to put the e modifier. So the preg_replace looks like this:

Code: Select all

$new_text = preg_replace('/{([^0-9](?:[A-Z0-9\-_]+))\}/e', '(isset($mytest->data[\'\\1\'])) ? $mytest->data[\'\\1\'] : \'\'', $text);

Re: [SOLVED] Problem with regex and backreference

Posted: Mon Dec 20, 2010 10:09 am
by ridgerunner
You may also wish to try using a callback function with preg_replace_callback(). This is typically a bit faster than using the 'e' modifier.