[SOLVED] Problem with regex and backreference

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

[SOLVED] Problem with regex and backreference

Post 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. :)
dreamline
Forum Contributor
Posts: 158
Joined: Fri May 28, 2004 2:37 am

Re: [SOLVED] Problem with regex and backreference

Post 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);
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: [SOLVED] Problem with regex and backreference

Post 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.
Post Reply