Php preg_replace, regex pattern doesn't match

I'm trying to develop a basic template engine, so I have to use preg_replace so much. I've a problem about below subject:

$subject = "{%content%} %content%";
$pattern = '/matched_regex/';
$replace = 'OK';
echo preg_replace($pattern,$replace,$subject);

and the output must be like this:

{%content%} OK

in other words it will be just matched with %content%

What should I do regex pattern?

Upvotes: 0

Views: 177

Answers (1)

mhall
mhall

Reputation: 3701

This will match only %content% that is not following an { or is at the beginning of the subject string. Any character that was before the %content% is put back with the \1 in the replacement string:

$subjects = [
    '{%content%} %content%',
    'Foo {%content%} bar %content% baz',
    'Foo{%content%}bar%content%baz',
    'Foo{%content%}bar%content%',
    '{%content%}%content%',
    '%content%{%content%}',
];

$replace = 'OK';
foreach ($subjects as $subject) {
    $pattern = '/(^|[^{])%content%/';
    echo preg_replace($pattern, '\1'.$replace, $subject), PHP_EOL;
}

Output:

{%content%} OK
Foo {%content%} bar OK baz
Foo{%content%}barOKbaz
Foo{%content%}barOK
{%content%}OK
OK{%content%}

Upvotes: 1

Related Questions