2

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 1

5

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

Regex demo | Php demo

$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"
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why (?!^) is needed?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.