[英]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. 我正在尝试开发基本的模板引擎,因此我必须使用preg_replace。 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%
换句话说,它将与
%content%
匹配
What should I do regex pattern? 我该怎么做正则表达式模式?
This will match only %content%
that is not following an {
or is at the beginning of the subject string. 这只会匹配不在主题字符串开头
{
或之后的%content%
。 Any character that was before the %content%
is put back with the \\1
in the replacement string: %content%
之前的任何字符都将在替换字符串中以\\1
放回:
$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%}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.