Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inverse of preg_quote in PHP

Tags:

regex

php

inverse

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
like image 769
ibrahim Avatar asked Feb 21 '23 14:02

ibrahim


1 Answers

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.

like image 182
Willem Mulder Avatar answered Mar 05 '23 05:03

Willem Mulder