Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP regex groups captures

Tags:

regex

php

I have the following regex:

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

This match the following successfully:

[abc - def - ghi - jkl]

BUT the match is:

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

What I need is something like this:

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

I'm able to do that in C# looking at the groups "captures". How can I do that in PHP?

like image 808
carlosdubusm Avatar asked Apr 12 '11 23:04

carlosdubusm


People also ask

What are capture groups regex?

Advertisements. Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d", "o", and "g".

What is first capturing group in regex?

/^(\d+)\s\1\s\1$/ this regex explains: (i) a caret ( ^ ) is at the beginning of the entire regular expression, it matches the beginning of a line. (ii) (\d+) is the first capturing group that finds any digit from 0-9 appears at least one or more times in the string.

What is non capturing group in regex?

tl;dr non-capturing groups, as the name suggests are the parts of the regex that you do not want to be included in the match and ?: is a way to define a group as being non-capturing. Let's say you have an email address [email protected] . The following regex will create two groups, the id part and @example.com part.

What is Preg_match?

The preg_match() function returns whether a match was found in a string.


1 Answers

This is not the job for the regexp. Match against \[([^\]]*)\], then split the first capture by the " - ".

<?php                                                                       
  $str = "[abc - def - ghi - jkl]";
  preg_match('/\[([^\]]*)\]/', $str, $re);
  $strs = split(' - ', $re[1]);
  print_r($strs);
?>
like image 184
Amadan Avatar answered Oct 08 '22 19:10

Amadan