2

Having trouble with a regular expression (they are not my strong suit). I'm trying to match all strings between {{ and }}, but if a set of brackets occurs on the same line, it counts that as a single match... Example:

$string = "
  Hello, kind sir
  {{SHOULD_MATCH1}} {{SHOULD_MATCH2}}
  welcome to
  {{SHOULD_MATCH3}}
  ";

preg_match_all("/{{(.*)}}/", $string, $matches);

var_dump($matches); // returns arrays with 2 results instead of 3

returns:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(35) "{{SHOULD_MATCH1}} {{SHOULD_MATCH2}}"
    [1]=>
    string(17) "{{SHOULD_MATCH3}}"
  }
  [1]=>
  array(2) {
    [0]=>
    string(31) "SHOULD_MATCH1}} {{SHOULD_MATCH2"
    [1]=>
    string(13) "SHOULD_MATCH3"
  }
}

Any help? Thanks!

2 Answers 2

5

Replace the * quantifier with its non-greedy form *?.

This will make it match as little as possible while still allowing the expression to match as a whole, which is different from its current behavior of matching as much as possible.

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

2 Comments

Or you can add the flag "U" to force non-greedy mode. Like preg_match_all("/{{(.*)}}/U", $string, $matches)
Accepted for explanation, thanks Jon. +1 to Fab Sa for a correct answer as well.
1

You can use one the following patterns.

  1. {{(.+?)}
  2. {{([^}]+)
  3. {{(\w+)
  4. {{([[:digit:][:upper:]_]+)
  5. {{([\p{Lu}\p{N}_]+)

Comments

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.