PHP regex groups commit

I have the following regex:

\[([^ -\]]+)( - ([^ -\]]+))+\] 

This corresponds to the following result:

 [abc - def - ghi - jkl] 

BUT the match corresponds to:

 Array ( [0] => [abc - def - ghi - jkl] [1] => abc [2] => - jkl [3] => jkl ) 

I need something like this:

 Array ( [0] => [abc - def - ghi - jkl] [1] => abc [2] => - def [3] => def [4] => - ghi [5] => ghi [6] => - jkl [7] => jkl ) 

I can do this in C # by looking at groups of "captures." How can I do this in PHP?

+7
source share
4 answers

This is not a regular expression job. Map to \[([^\]]*)\] , then split first capture " - " .

 <?php $str = "[abc - def - ghi - jkl]"; preg_match('/\[([^\]]*)\]/', $str, $re); $strs = split(' - ', $re[1]); print_r($strs); ?> 
+8
source

Assuming the tokens in your sample string do not contain spaces and are alphanumeric:

 <?php $pattern = "/([\w|\d])+/"; $string = "[abc - 123 - def - 456 - ghi - 789 - jkl]"; preg_match_all($pattern, $string, $matches); print_r($matches[0]); ?> 

Output:

 Array ( [0] => abc [1] => 123 [2] => def [3] => 456 [4] => ghi [5] => 789 [6] => jkl ) 
+9
source

SPL preg_match_all will return regex groups starting at index 1 of the $matches variable. If you want to get only the second group, you can use $matches[2] , for example.

Syntax:

 $matches = array(); preg_match_all(\ '/(He)\w+ (\w+)/', "Hello world\n Hello Sunshine", $matches ); var_dump($matches); 

Result:

 array(3) { [0] => array(2) { [0] => string(11) "Hello world" [1] => string(14) "Hello Sunshine" } [1] => array(2) { [0] => string(2) "He" [1] => string(2) "He" } [2] => array(2) { [0] => string(5) "world" [1] => string(8) "Sunshine" } } 

PS This answer is published for the context of the name of the question after it was sent here by Google search. This was the information that interested me when searching for this topic.

+4
source

Use parentheses to group your matches. EG:

 $string = 'bob'; preg_match('/bob/', $string, $matches); 

$matches will be ['bob']

 preg_match('/(b)(o)(b)/', $string, $matches); 

$matches will be ['b','o','b']

+3
source

All Articles