Given the input string "othertext ?.abc.de.fgh.i moretext" and the pattern '/\?(\.[a-zA-Z]*)*/' I'm trying to use function preg_match_all to get an array of matches with the elements .abc, .de, .fgh, and .i but only ?.abc.de.fgh.i and .i are matched. (The test)
1 Answer
You could make use of the \G anchor
(?:\?|\G(?!^))\K\.[a-zA-Z]+
In parts:
(?:Non capture group\?Match?|Or\G(?!^)Assert position at the end of previous match, not at the start
)Close group\K\.[a-zA-Z]+Forget what is currently matched, and match the.and 1+ chars a-zA-Z
$re = '/(?:\?|\G(?!^))\K\.[a-zA-Z]+/';
$str = 'othertext ?.abc.de.fgh.i moretext';
preg_match_all($re, $str, $matches);
var_dump($matches[0]);
Output
array(4) {
[0]=>
string(4) ".abc"
[1]=>
string(3) ".de"
[2]=>
string(4) ".fgh"
[3]=>
string(2) ".i"
}
2 Comments
Oleg
Why
(?!^) is needed?The fourth bird
@Oleg that is because the
\G matches at 2 positions. At the start of the string or at the position of the previous match. See this page for more information rexegg.com/regex-anchors.html#G