0

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?

2
  • I've tried this $pattern = '/[^{]%\s*(.*?)\s*%[^}]/'; Commented Mar 2, 2015 at 21:31
  • and this $pattern = '/{{0}?%\s*(.*?)\s*%}{0}/'; Commented Mar 2, 2015 at 21:35

1 Answer 1

1

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%}
Sign up to request clarification or add additional context in comments.

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.