Maria Gabriela
Maria Gabriela

Reputation: 137

PHP regular expression matching

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)

Upvotes: 2

Views: 152

Answers (1)

The fourth bird
The fourth bird

Reputation: 163217

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"
}

Upvotes: 5

Related Questions