0

How can I check for a variable number of elements in a string?

[keyword1|keyword2|keyword3]
[keyword1|keyword2]

... or more than three keywords. This would just work for three elements:

preg_match("/^\[(.*)\|(.*)\|(.*)\]$/",$string, $matches)

Edit: How can I get the captured keyword in variables? i.e.:

matches[1] = keyword1
matches[2] = keyword2
matches[3] = keyword3
user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

2

You can use:

(?:^\[(?=[^][|]*(?:\|[^][|]*)*\])|(?!^)\G)([^][|]*)(?:[]|])

Regular expression visualization

DEMO

This technique is explained in details HERE

Community
  • 1
  • 1
Enissay
  • 4,969
  • 3
  • 29
  • 56
  • @user3142695 It looks scary, but once you read the doc (link above) you'll see how much it's simple :) – Enissay Dec 26 '14 at 16:27
  • @AvinashRaj it's true that the `(?=...)` is not needed here, it only controls how many results to grab... Removing it will give a similar pattern to yours, so I'll leave it – Enissay Dec 26 '14 at 17:05
1

Use this, 3 and more.

^\[[^|\n]*(?:\|[^|\n]*){2,}\]$

DEMO

FOr more than 3,

^\[[^|\n]*(?:\|[^|\n]*){3,}]$

DEMO

You could do simply like this through \G anchor,

(?:^\[|\G)\|?([^\n|\]]+)(?=[\]|])

Use \G anchor to do a continuous string match.

DEMO

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274