Dannyboy
Dannyboy

Reputation: 2052

PHP pcre regex to find content of curly brackets

I need PHP pcre regex to find content of all curly brackets... Why is this regex doesn't work?

<?php

    $str = "test{it}test{/it}test";
    $ret = preg_match_all("#\{.?\}#u", $str, $matches);
    print_r($matches);

?>

I expect $matches to contain {it} and {/it} - but it's empty....

Upvotes: 1

Views: 180

Answers (2)

Andie2302
Andie2302

Reputation: 4887

What your regex does:

\{.?\}
  • Match the character “{” literally.
  • Match any single character that is not a line break character between zero and one times, as many times as possible, giving back as needed.
  • Match the character “}” literally.

What you want from your regex:

\{.*?\}
  • Match the character “{” literally.
  • Match any single character that is not a line break character between zero and unlimited times, as few times as possible, expanding as needed.
  • Match the character “}” literally.

Upvotes: 3

Dalorzo
Dalorzo

Reputation: 20014

I think this is the version you are looking for: {.*?} with the * before the ?

$re = "/{.*?}/"; 
$str = "test{it}test{/it}test"; 

preg_match_all($re, $str, $matches);

Upvotes: 1

Related Questions