我需要编写一个与 preg_quote 函数完全相反的函数。简单地删除所有“\”是行不通的,因为字符串中可能有一个“\”。
例子;
inverse_preg_quote('an\\y s\.tri\*ng') //this should return "an\y s.tri*ng"
或者你可以测试为
inverse_preg_quote(preg_quote($string)) //$string shouldn't change
你正在寻找stripslashes
<?php
$str = "Is your name O\'reilly?";
// Outputs: Is your name O'reilly?
echo stripslashes($str);
?>
有关详细信息,请参阅http://php.net/manual/en/function.stripslashes.php。(还有更通用的http://www.php.net/manual/en/function.addcslashes.php和http://www.php.net/manual/en/function.stripcslashes.php你可能想要调查 )
编辑:否则,您可以进行三个 str_replace 调用。首先将\\替换为例如$DOUBLESLASH,然后将\替换为“”(空字符串),然后将$DOUBLESLASH设置回\。
$str = str_replace("\\", "$DOUBLESLASH", $str);
$str = str_replace("\", "", $str);
$str = str_replace("$DOUBLESLASH", "\", $str);
有关更多信息,请参阅http://php.net/manual/en/function.str-replace.php。
从手册:
特殊的正则表达式字符是: . \ + * ? [ ^ ] $ ( ) { } = !< > | : -
您可以编写一个函数,用\
字符本身替换上述每个字符。应该很容易:
function inverse_preg_quote($str)
{
return strtr($str, array(
'\\.' => '.',
'\\\\' => '\\',
'\\+' => '+',
'\\*' => '*',
'\\?' => '?',
'\\[' => '[',
'\\^' => '^',
'\\]' => ']',
'\\$' => '$',
'\\(' => '(',
'\\)' => ')',
'\\{' => '{',
'\\}' => '}',
'\\=' => '=',
'\\!' => '!',
'\\<' => '<',
'\\>' => '>',
'\\|' => '|',
'\\:' => ':',
'\\-' => '-'
));
}
$string1 = '<title>Hello (World)?</title>';
$string2 = inverse_preg_quote(preg_quote($string1));
echo $string1 === $string2;
您可以使用专用的 T-Regx 库:
Pattern::unquote('an\\y s\.tri\*ng'); // 'any s.tri*ng'