Search code examples
phpregexinverse

Inverse of preg_quote in PHP


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

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.