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
3
  • did you want for 3 and more? Commented Dec 26, 2014 at 16:12
  • You'll need two separate patterns, one to validate the string, and one to extract the keywords. Commented Dec 26, 2014 at 16:12
  • @AvinashRaj: Variable Number, that means 1 or more keyword in that string (beginning with [ and ending with ]) Commented Dec 26, 2014 at 16:13

2 Answers 2

2

You can use:

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

Regular expression visualization

DEMO

This technique is explained in details HERE

Sign up to request clarification or add additional context in comments.

2 Comments

@user3142695 It looks scary, but once you read the doc (link above) you'll see how much it's simple :)
@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
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

5 Comments

preg_match("/^\[[^|\n]*(?:\|[^|\n]*){2,}\]$/",$string, $matches) So my result would be: $matches[1], $matches[2], ... $matches[n]. Correct?
no, it matches that particular line only. Did you want to capture the keywords? Could you edit the question with expected output?
Yes, sorry for the unsufficient question. Updated the question.
In the regex101.com-link every second result is empty? match1 = 'keyword 1', match2 = '' and so on...
I think you could filter out the empty strings from an array easily.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.