Do you have a question? Post it now! No Registration Necessary. Now with pictures!
- Posted on
September 9, 2012, 10:31 am
rate this thread
$pattern = array();
foreach ($filter as $org)
$text = preg_replace($pattern, '$1$new$3', $text);
The issue I'm having is when $org contains a regex expression, like:
in which case (er|in|...) would now be $4 instead of $3.
The question is, is there a way that I can dynamically find the last backre=
ference in the pattern, instead of referring to it strictly by number?
If not, I could always check to see if $org contains a (...), and then set =
the number accordingly. But this is in a foreach loop, and putting an strpo=
s() in a loop like that seems slow; and then, I'm not sure that a backrefer=
ence like this would works. Like:
if (strpos...) $num = "4";
else $num = "3";
$text = preg_replace($pattern, '$1$new$$num', $text);
- Anders Wegge Keller
September 9, 2012, 11:51 am
Re: Dynamic backreferences, finding last in a group
Wow that is a very good feature I never know about.
This I can imagine will come in very handy.
Example #4 Using named subpattern
$str = 'foobar: 2008';
preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches);
/* This also works in PHP 5.2.2 (PCRE 7.0) and later, however
* the above form is recommended for backwards compatibility */
// preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches);
The above example will output:
 => foobar: 2008
[name] => foobar
 => foobar
[digit] => 2008
 => 2008