Jonas Geiler
Jonas Geiler

Reputation: 193

Capture between round brackets and square brackets

I have a text similar to this:

[text]
(more text)
(text...)
[text!]
(last text)

I need to match the text between () and [].
The output should be something like this:

[
  "text",
  "more text",
  "text...",
  "text!",
  "last text"
]

I already tried /[\[\(](.*?)[\]\)]/ but it didn't work in PHP.
Here is the code if you need it:

 preg_match_all('/[\[\(](.*?)[\]\)]/', $text, $matches, PREG_SET_ORDER, 0);
 var_dump($matches);

How do I achieve this using regex in PHP?

Thanks in advance,
Skayo

Upvotes: 0

Views: 71

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627537

I would suggest a regex based on a branch reset feature:

$re = '/(?|\[([^]]*)]|\(([^)]*)\))/';
$str = '[text]
(more text)
(text...)
[text!]
(last text)';

preg_match_all($re, $str, $matches);

See the PHP demo

See the regex demo

  • (?| - start of the branch reset
  • \[ - a [
  • ([^]]*) - any 0+ chars other than ]
  • ] - a literal ]
  • | - or
  • \( - a literal (
  • ([^)]*) - any 0+ chars other than )
  • \) - a literal )
  • ) - end of the branch reset group.

Upvotes: 2

rickdenhaan
rickdenhaan

Reputation: 11328

Actually, that code works like a charm. You just need to add a line to filter out the matched sections:

$texts = array_column($matches, 1);

See https://3v4l.org/uCHIB for a working example.

Upvotes: 2

Related Questions