Kyle Piontek
Kyle Piontek

Reputation: 185

Regex to find html in between curly brackets in PHP

I'm new to regex and I am having some trouble. I'm trying the get everything between {{#user_data?}} and {{/user_data?}}

$content = '
{{#user_data?}}
<span class="hello">
Hello, {{username}}!
</span>
{{/user_data?}}';

$key = 'user_data?';
$regex = '/\{\{#'.$key.'\}\}(.*?)\{\{\/'.$key.'\}\}/';
if (preg_match_all($regex, $content, $matches))
{
print_r($matches);
}
else
echo 'no match found';

What am I doing wrong?

Upvotes: 1

Views: 238

Answers (1)

Passerby
Passerby

Reputation: 10070

In addition to comments' "not escaping ? sign", you also need proper modifiers:

$content = <<<STR
{{#user_data?}}
<span class="hello">
Hello, {{username}}!
</span>
{{/user_data?}}
STR;

$key = 'user_data\?';
$regex = '/\{\{#'.$key.'\}\}(.*?)\{\{\/'.$key.'\}\}/sim';
preg_match_all($regex, $content, $matches,PREG_SET_ORDER);
print_r($matches);

This will output:

Array
(
    [0] => Array
        (
            [0] => {{#user_data?}}
<span class="hello">
Hello, {{username}}!
</span>
{{/user_data?}}
            [1] => 
<span class="hello">
Hello, {{username}}!
</span>

        )

)

i is not necessary, and should be removed if you need case-sensitive template;

m may be unnecessary too, according to PHP Document about PCRE modifiers;

s is a must, so you can match multiline string with dot.

Upvotes: 2

Related Questions