Question

I need to write a function that does exactly opposite of preg_quote function. Simply removing all '\' did not work because there can be a '\' in the string.

Example;

inverse_preg_quote('an\\y s\.tri\*ng') //this should return "an\y s.tri*ng" 

or you can test as

inverse_preg_quote(preg_quote($string)) //$string shouldn't change
Was it helpful?

Solution

You are looking for stripslashes

<?php
    $str = "Is your name O\'reilly?";

    // Outputs: Is your name O'reilly?
    echo stripslashes($str);
?>

See http://php.net/manual/en/function.stripslashes.php for more info. ( There's also the slightly more versatile http://www.php.net/manual/en/function.addcslashes.php and http://www.php.net/manual/en/function.stripcslashes.php you might want to look into )

Edit: otherwise, you could do three str_replace calls. The first to replace \\ with e.g. $DOUBLESLASH, and then replace \ with "" (empty string), then set $DOUBLESLASH back to \.

$str = str_replace("\\", "$DOUBLESLASH", $str);
$str = str_replace("\", "", $str);
$str = str_replace("$DOUBLESLASH", "\", $str);

See http://php.net/manual/en/function.str-replace.php for more info.

OTHER TIPS

From the manual:

The special regular expression characters are: . \ + * ? [ ^ ] $ ( ) { } = ! < > | : -

You can write a function that replaces \ followed by each of the above characters with the character itself. Should be easy:

function inverse_preg_quote($str)
{
    return strtr($str, array(
        '\\.'  => '.',
        '\\\\' => '\\',
        '\\+'  => '+',
        '\\*'  => '*',
        '\\?'  => '?',
        '\\['  => '[',
        '\\^'  => '^',
        '\\]'  => ']',
        '\\$'  => '$',
        '\\('  => '(',
        '\\)'  => ')',
        '\\{'  => '{',
        '\\}'  => '}',
        '\\='  => '=',
        '\\!'  => '!',
        '\\<'  => '<',
        '\\>'  => '>',
        '\\|'  => '|',
        '\\:'  => ':',
        '\\-'  => '-'
    ));
}
$string1 = '<title>Hello (World)?</title>';
$string2 = inverse_preg_quote(preg_quote($string1));
echo $string1 === $string2;

You can use dedicated T-Regx library:

Pattern::unquote('an\\y s\.tri\*ng'); // 'any s.tri*ng'
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top