regex - Get all matched groups PREG PHP flavor -


pattern : '/x(?: (\d))+/i'

string : x 1 2 3 4 5

returned : 1 match position[11-13] '5'

i want catch possible repetitions, or return 1 result per group?

i want following :

desired output:

match 1 1.  [4-5]   `1` 2.  [6-7]   `2` 3.  [8-9]   `3` 4.  [10-11] `4` 5.  [12-13] `5` 

which able achieve copy pasting group, not want. want dynamic group capturing

pattern: x(?: (\d))(?: (\d))(?: (\d))(?: (\d))(?: (\d))

you cannot use 1 group capture multiple texts , access them pcre. instead, can either match whole substring \d+(?:\s+\d+)* , split space:

$re2 = '~\d+(?:\s+\d+)*~'; if (preg_match($re2, $str, $match2)) {     print_r(preg_split("/\\s+/", $match2[0])); } 

alternatively, use \g based regex return multiple matches:

(?:x|(?!^)\g)\s*\k\d+ 

see demo

here php demo:

$str = "x 1 2 3 4 5";  $re1 = '~(?:x|(?!^)\g)\s*\k\d+~';  preg_match_all($re1, $str, $matches); var_dump($matches); 

here, (?:x|(?!^)\g) acting leading boundary (match whitespaces , digits after x or each successful match). when digits encountered, characters matched far omitted \k operator.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

How to get the ip address of VM and use it to configure SSH connection dynamically in Ansible -

javascript - Get parameter of GET request -