Mike
Mike

Reputation: 2374

PHP preg_match_all same line

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!

Upvotes: 2

Views: 1440

Answers (2)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57670

You can use one the following patterns.

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

Upvotes: 1

Jon
Jon

Reputation: 437554

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.

Upvotes: 5

Related Questions