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:

JavaScript

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

JavaScript

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

JavaScript

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

Thoughts?

Advertisement

Answer

You can use

JavaScript

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:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement