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?
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".
/^(\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.
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.
The preg_match() function returns whether a match was found in a string.
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With