如何在单个函数中使用反斜杠预先添加某些字符?
相当于做了一堆str_replace
s:
$text = "asdf[],.\?'";
$text = str_replace("'","\'", $text);
$text = str_replace("s","\s", $text);
$text = str_replace("[","\[", $text);
...etc...
我想传递一个像正则表达式一样的字符类,但不知道如何让preg_replace
前置反斜杠而不是替换它。
$text = preg_replace("/['s\[]/","\{$var?}",$text);
我可以在数组中设置字符并循环遍历它,但我似乎记得有一个函数可以做到这一点。
答案 0 :(得分:4)
如果要使用反斜杠转义单个字符,请使用addcslashes()
:
$text = "asdf[],.\?'";
echo addcslashes($text, "'s[");
输出:
a\sdf\[],.\?\'
答案 1 :(得分:1)
只需在替换部件中添加四个反斜杠,
<?php
$text = "asdf[],.\?'";
echo preg_replace("/(['s\[])/","\\\\$1",$text);
?>
<强>输出:强>
a\sdf\[],.\?\'