user3142695
user3142695

Reputation: 17372

Searching for multiple elements with regex

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

Upvotes: 0

Views: 50

Answers (2)

Avinash Raj
Avinash Raj

Reputation: 174874

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

Upvotes: 1

Enissay
Enissay

Reputation: 4953

You can use:

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

Regular expression visualization

DEMO

This technique is explained in details HERE

Upvotes: 2

Related Questions