4

我需要编写一个与 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
4

3 回答 3

5

你正在寻找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.phphttp://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

于 2012-02-07T08:14:12.303 回答
3

手册

特殊的正​​则表达式字符是: . \ + * ? [ ^ ] $ ( ) { } = !< > | : -

您可以编写一个函数,用\字符本身替换上述每个字符。应该很容易:

function inverse_preg_quote($str)
{
    return strtr($str, array(
        '\\.'  => '.',
        '\\\\' => '\\',
        '\\+'  => '+',
        '\\*'  => '*',
        '\\?'  => '?',
        '\\['  => '[',
        '\\^'  => '^',
        '\\]'  => ']',
        '\\$'  => '$',
        '\\('  => '(',
        '\\)'  => ')',
        '\\{'  => '{',
        '\\}'  => '}',
        '\\='  => '=',
        '\\!'  => '!',
        '\\<'  => '<',
        '\\>'  => '>',
        '\\|'  => '|',
        '\\:'  => ':',
        '\\-'  => '-'
    ));
}
$string1 = '<title>Hello (World)?</title>';
$string2 = inverse_preg_quote(preg_quote($string1));
echo $string1 === $string2;
于 2012-02-07T08:14:29.337 回答
0

您可以使用专用的 T-Regx 库

Pattern::unquote('an\\y s\.tri\*ng'); // 'any s.tri*ng'
于 2019-05-23T10:39:56.587 回答