PHP preg_replace模式似乎只有在错误时才有效


PHP preg_replace pattern only seems to work if its wrong?

我有一个看起来像这样的字符串

../Clean_Smarty_Projekt/tpl/templates_c'.
../Clean_Smarty_Projekt/tpl/templates_c'..

我想用正则表达式替换../'.'..

以前,我是这样做的:

$result = str_replace(array("../","'..","'."),"",$str);

它(模式)必须按这个顺序排列,因为更改它会使输出有点错误。所以我决定使用正则表达式。

现在我想出了这个模式

$result = preg_replace('/('.'.'/)|(''['.]{1,2})/',"",$str);

实际上只返回空字符串...

原因:(''['.]{1,2})

在正则表达式 101 中一切正常。(花了几分钟才意识到我不需要preg_replace中的/g

如果我在preg_replace中使用此模式,我必须执行(''''['.]{1,2})才能使其工作。但这显然是错误的,因为我没有搜索两个斜杠。

我当然知道转义的斜杠(转义斜杠)。

为什么这不匹配?

我建议你使用不同的php分隔符。在/分隔符中,需要使用三个'''或四个''''反斜杠来匹配单个反斜杠。

$string = '../Clean_Smarty_Projekt/tpl/templates_c'.'."'n".'../Clean_Smarty_Projekt/tpl/templates_c'..';
echo preg_replace('~'.'./|'''.{1,2}~', '', $string)

输出:

Clean_Smarty_Projekt/tpl/templates_c
Clean_Smarty_Projekt/tpl/templates_c