我有这行文字:
This is {{some. test}} to see if I can remove spaces
我想要这行使用正则表达式的文本:
This is {{some.test}} to see if I can remove spaces
我已经尝试过这个问题来进入正确的方向,尽管我可以将所有的多个空间与([ 't]+[ ])+
进行匹配,但我不知道如何仅在{{
和}}
之间进行匹配。
如何修改当前的正则表达式?
要删除{{...}}
中的所有空格,可以用{{.*?}}
正则表达式匹配{{...}}
子字符串,并用preg_replace_callback
:替换这些匹配中的空格
$re = '~{{.*?}}~s';
$str = "This is {{some. test}} to see if I can remove spaces";
echo preg_replace_callback($re, function($m) {
return str_replace(" ", "", $m[0]);
}, $str);
查看IDEONE演示
s
修饰符也将使.
与换行符匹配。如果您不需要(并且只想匹配一行中的{{...}}
子字符串,请删除s
。
要替换所有类型的空白,请在回调中使用preg_replace
,'s+
模式匹配1+个空白字符:
preg_replace('~'s+~', '', $m[0])