RegEx - Positive Lookbehind Problem
How do I use a positive look-behind to match more than 1 occurrence using a greedy +
?
This works:
(?<=\w)\w+
But I need to match all \w similar to:
开发者_StackOverflow (?<=\w+)\w+
The syntax is wrong in the second example and it does not work.
How do I make a positive lookbehind match multiple occurrences?
A very dirty way to do it is to reverse the string and use a positive lookahead instead. This is a trick that I use in Javascript (no lookbehinds supported there :( ).
So you must do something like:
$string = 'This is a long string that must show this is what will happen';
$str_rev = strrev($string);
if (preg_match('!(si)(?=\w+)(\w+)!i', $str_rev, $matches)) {
print_r($matches);
}
The code above will match is in the occurrences of THIS in the string. The second \w+ is just to show where it matched and is not needed in your example.
Keep in mind that this technique is possible only if you use only one direction for greediness for the Lookbehind/aheads (e.g. you can't use a lookbehind with \w+ together with a lookahead with \w+ )
You probably just want to match it without any lookbehinds and then use your capturing groups:
if (preg_match('~[abc]+([cde]+)~', $string, $matches)) {
echo $matches[1]; // will contain the [cde]+ part
}
Sorry to say, but no quantifiers in lookbehinds!
I found this in the perlretut
Lookahead (?=regexp) can match arbitrary regexps, but lookbehind (?<=fixed-regexp) only works for regexps of fixed width
I assume that this is also valid for the php regex engine.
精彩评论