Dynamic backreferences, finding last in a group [message #179065] |
Sun, 09 September 2012 10:31 |
jwcarlton
Messages: 76 Registered: December 2010
Karma: 0
|
Member |
|
|
I'm working with preg_replace(), like so:
$pattern = array();
foreach ($filter as $org)
array_push($pattern, "/((<br>|\s)*)$org(er|in|...)/i");
$text = preg_replace($pattern, '$1$new$3', $text);
The issue I'm having is when $org contains a regex expression, like:
(D|d)ear
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 backreference 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 strpos() in a loop like that seems slow; and then, I'm not sure that a backreference like this would works. Like:
if (strpos...) $num = "4";
else $num = "3";
$text = preg_replace($pattern, '$1$new$$num', $text);
Any suggestions?
|
|
|
|
Re: Dynamic backreferences, finding last in a group [message #179067 is a reply to message #179066] |
Sun, 09 September 2012 14:16 |
Scott Johnson
Messages: 196 Registered: January 2012
Karma: 0
|
Senior Member |
|
|
On 9/9/2012 4:51 AM, Anders Wegge Keller wrote:
> Jason C <jwcarlton(at)gmail(dot)com> writes:
>
>> Any suggestions?
>
> Read the manual on regexp syntax, and use named patterns.
>
Wow that is a very good feature I never know about.
This I can imagine will come in very handy.
Thanks
Scotty
Example #4 Using named subpattern
<?php
$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);
print_r($matches);
?>
The above example will output:
Array
(
[0] => foobar: 2008
[name] => foobar
[1] => foobar
[digit] => 2008
[2] => 2008
)
|
|
|