[英]php regex to replace spaces in braces including braces
I wonder if it's possible to solve such kind of template parsing using RegEx-es I have text similar to:我想知道是否可以使用 RegEx-es 解决这种模板解析问题,我的文本类似于:
'Hello, {{ Na me|{{Surname }}}}. Would you like some drink? {{CoffeePreferred? We have a special discount for coffee}} {{Tea Preferred? We have a special discount for tea}}'
First, I need to fix errors in variable names (variables must always come right after braces to special symbol like "?" or "|" or something else could be comma or dot - it means rules can be added in future).首先,我需要修复变量名称中的错误(变量必须始终紧跟在大括号后面的特殊符号,如“?”或“|”或其他可以是逗号或点的东西 - 这意味着将来可以添加规则)。
Na me
, Tea Preferred
Surname
are spelling errors of variable names. Na me
, Tea Preferred
Surname
是变量名的拼写错误。 Also variable names should start with right after curly braces contain no spaces after - otherwise it's also an error.此外,变量名应该在大括号之后不包含空格后立即开始 - 否则它也是一个错误。
Then I need to keep text as is.然后我需要保持文本原样。
But Dear friend , We have a special discount for coffee and We have a special discount for tea are simple text.但是亲爱的朋友,我们有咖啡特别折扣和我们有茶特别折扣是简单的文字。
So my question is how can I replace unnecessary spaces withing underscores in variables and keep them in text?所以我的问题是如何用变量中的下划线替换不必要的空格并将它们保留在文本中? Also I want to make it in as fewer steps as possible (due to performance impact and my texts can take megabytes).
此外,我希望尽可能减少步骤(由于性能影响和我的文本可能占用兆字节)。
I expect my text to be:我希望我的文字是:
'Hello, {{Na_me|{{Surname}}}}. Would you like some drink? {{CoffeePreferred? We have a special discount for coffee}} {{Tea_Preferred? We have a special discount for tea}}'
My first step was to extract content of braces:我的第一步是提取大括号的内容:
preg_replace_callback(
'/(\{\{)(.*?)(\}\})/ui',
function ($matches) {
echo $matches[2];
});
Then I tried to replace spaces by rules described above with no success.然后我尝试用上述规则替换空格,但没有成功。 I tried to use assertions like
/[\\s](?!<=\\|)/
and expressions like (\\s(?!\\|))|((?!\\|)\\s)
Does anybody have any idea?我尝试使用像
/[\\s](?!<=\\|)/
这样的断言和像(\\s(?!\\|))|((?!\\|)\\s)
这样的表达式有人知道吗?
Here is a way to do the job:这是完成这项工作的一种方法:
$str = preg_replace_callback(
'/\{\{([^|?{}]+)/',
function ($matches) {
$ret = trim($matches[1]);
return preg_replace('/ /', '_', $ret);
},
$str
);
After that you can remove all the braces:之后,您可以删除所有大括号:
$str = preg_replace('/[{}]+/', '', $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.