Skip to content
Advertisement

Pregmatch to get contents between square brackets php

I thought I found a solution here on stack that would work, but I might be going about it wrong:

$subject = 'RE: Reply to me [Quote #341 | some-site]';

preg_match("/[[^]]*]/", $subject, $matches);

var_dump($matches);

what I am trying to do is create an array where it comes out as:

[
    "Quote ...",
    "some-site",
]

Now this regex is suppose to get me the contents, I think, from the square brackets but all I get is:

array(1) {
  [0]=>
  string(29) "[Quote #341 | some-site]"
}

Which is wrong. I want the contents inside the square brackets, with out the |

Thoughts?

Advertisement

Answer

You can use

[s*([^][|]*?)s*|s*([^][]*?)s*]

See the regex demo.

Details:

  • [ – a [ char
  • s* – zero or more whitespaces
  • ([^][|]*?) – Group 1: zero or more chars other than [, ] and | (as few as possible)
  • s*|s* – a | enclosed with zero or more whitespaces
  • ([^][]*?) – Group 1: zero or more chars other than [ and ] (as few as possible)
  • s* – zero or more whitespaces
  • ] – a ] char

See the PHP demo:

$re = '/[s*([^][|]*?)s*|s*([^][]*?)s*]/m';
$str = 'RE: Reply to me [Quote #341 | some-site]';
if (preg_match($re, $str, $match)) {
    array_shift($match);
    print_r($match);
}

Output:

Array
(
    [0] => Quote #341
    [1] => some-site
)
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement