virrion virrion - 4 months ago 12
PHP Question

Another regex: square brackets

I have something like:

word[val1|val2|val3]
. Need a regex to capture both: word and val1|val2|val3

Another sample:
leader[77]

Result: Need a regex to capture both: leader and 77

This is what I have so far:
^(.*\[)(.*)
and it gives me: array[0]=word[val1|val2|val3];

array[1]=word[

array[2]=val1|val2|val3]




array[1] is needed but without [

array[2] is needed but without ]

Any ideas? - Thank you

Answer

You can use

([^][]+)\[([^][]*)]

Here is the regex demo

Explanation:

  • ([^][]+) - Group 1 matching one or more chars other than ] and [
  • \[ - a literal [
  • ([^][]*) - Group 2 capturing 0+ chars other than [ and ]
  • ] - a literal ].

See IDEONE demo:

$re = '~([^][]+)\[([^][]*)]~'; 
$str = "word[val1|val2|val3]"; 
preg_match($re, $str, $matches);
echo $matches[1]. "\n" . $matches[2];