[英]regex expression with preg_replace in php
I have to replace some characters in a large string based on some rule: 我必须根据某些规则替换大字符串中的某些字符:
I'll try to give a couple of examples hoping it'll make it more clear than actually trying to explain the rule: 我将尝试给出一些示例,希望它比实际解释该规则更加清晰:
{{ @ text @@ text }}
should be {{ @ text # text}}
{{ @ text @@ text }}
应该是{{ @ text # text}}
@@ text {{ text 123 @ te@@xt @@ text 34@}}
should be @@ text {{ text 123 @ te#xt # text 34@}}
(if @@
is not between {{
and }}
it should get ignored; also, all @@
s between {{
and }}
should get replaced) @@ text {{ text 123 @ te@@xt @@ text 34@}}
应该是@@ text {{ text 123 @ te#xt # text 34@}}
(如果@@
不在{{
和}}
它应该被忽略;而且, {{
和}}
之间的所有@@
都应该被替换)
I tried $text = preg_replace("/({{.*)[@]{2}(.*}})/U", '\\\\1#\\\\2', $text);
我试过
$text = preg_replace("/({{.*)[@]{2}(.*}})/U", '\\\\1#\\\\2', $text);
but with no success. 但没有成功。
Thanks! 谢谢! :)
:)
As you can see here , "{" and "}" are reserved characters used for the start/end min/max quantifier. 如您在此处看到的,“ {”和“}”是保留字符,用于开始/结束最小/最大量词。 For this reason, you should backslash these characters in your pattern:
因此,您应该在模式中反斜杠这些字符:
$text = preg_replace("/(\{\{.*)[@]{2}(.*\}\})/U", '\\1#\\2', $text);
This will replace only one occurrence so you have to put your code in a loop like this: 这将仅替换一次出现的事件,因此您必须将代码放入这样的循环中:
$text = '@@ text {{ text 123 @ te@@xt @@ text 34@}}';
do
{
$textBefore = $text;
$text = preg_replace("/(\{\{.*)[@]{2}(.*\}\})/U", '\\1#\\2', $text);
} while($textBefore != $text);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.