stripslashes

(PHP 4, PHP 5, PHP 7)

stripslashes따옴표 처리한 문자열을 풉니다

설명

string stripslashes ( string $str )

따옴표 처리한 문자열을 풀어냅니다.

Note:

magic_quotes_sybase가 켜져 있으면, 백슬래시는 처리되지 않고, 이중 어퍼스트로피를 하나로 교체합니다.

PHP 지시어 magic_quotes_gpcon(기본값으로 on입니다)일 때, 데이터를 이스케이프가 필요한 장소(데이터베이스 등)에 놓지 않을 경우의 사용 예제입니다. 예를 들면, HTML 폼에서 전달한 데이터를 단순히 바로 출력할 경우입니다.

인수

str

입력 문자열.

반환값

백슬래시 처리를 제거한 문자열을 반환합니다. (\''이 됩니다) 이중 백슬래시(\\)는 백슬래시 하나(\)가 됩니다.

예제

Example #1 stripslashes() 예제

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

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

Note:

stripslashes()는 재귀하지 않습니다. 이 함수에 다차원 배열을 적용하려면, 재귀 함수를 사용해야 합니다.

Example #2 배열에 stripslashes() 사용하기

<?php
function stripslashes_deep($value)
{
    
$value is_array($value) ?
                
array_map('stripslashes_deep'$value) :
                
stripslashes($value);

    return 
$value;
}

// 예시
$array = array("f\\'oo""b\\'ar", array("fo\\'o""b\\'ar"));
$array stripslashes_deep($array);

// 출력
print_r($array);
?>

위 예제의 출력:

Array
(
    [0] => f'oo
    [1] => b'ar
    [2] => Array
        (
            [0] => fo'o
            [1] => b'ar
        )

)

참고

add a note add a note

User Contributed Notes 31 notes

up
65
ivijan dot stefan at gmail dot com
5 years ago
Sometimes for some reason is happens that PHP or Javascript or some naughty insert a lot of  backslash. Ordinary function does not notice that. Therefore, it is necessary that the bit "inflate":

<?php
function removeslashes($string)
{
   
$string=implode("",explode("\\",$string));
    return
stripslashes(trim($string));
}

/* Example */

$text="My dog don\\\\\\\\\\\\\\\\'t like the postman!";
echo
removeslashes($text);
?>

RESULT: My dog don't like the postman!

This flick has served me wery well, because I had this problem before.
up
6
shredder at technodrome dot com
10 years ago
Hi,

Here are recursive addslashes / stripslashes functions.
given a string - it will simply add / strip slashes
given an array - it will recursively add / strip slashes from the array and all of it subarrays.
if the value is not a string or array - it will remain unmodified!

<?php

function add_slashes_recursive( $variable )
{
    if (
is_string( $variable ) )
        return
addslashes( $variable ) ;

    elseif (
is_array( $variable ) )
        foreach(
$variable as $i => $value )
           
$variable[ $i ] = add_slashes_recursive( $value ) ;

    return
$variable ;
}

function
strip_slashes_recursive( $variable )
{
    if (
is_string( $variable ) )
        return
stripslashes( $variable ) ;
    if (
is_array( $variable ) )
        foreach(
$variable as $i => $value )
           
$variable[ $i ] = strip_slashes_recursive( $value ) ;
   
    return
$variable ;
}

?>
up
2
Kibby
13 years ago
Okay, if using stripslashes_deep, it will definitely replace any NULL to "".  This will affect to coding that depends isset().  Please provide a workaround based on recent note.
up
3
StefanoAI
6 years ago
Recursive stripslashes
<?php
if (get_magic_quotes_gpc()) {

    function
stripslashes_array(&$arr) {
        foreach (
$arr as $k => &$v) {
           
$nk = stripslashes($k);
            if (
$nk != $k) {
               
$arr[$nk] = &$v;
                unset(
$arr[$k]);
            }
            if (
is_array($v)) {
               
stripslashes_array($v);
            } else {
               
$arr[$nk] = stripslashes($v);
            }
        }
    }

   
stripslashes_array($_POST);
   
stripslashes_array($_GET);
   
stripslashes_array($_REQUEST);
   
stripslashes_array($_COOKIE);
}
?>
up
1
o-zone at zerozone dot it
10 years ago
If you need to remove all slashes from a string, here's a quick hack:

<?php
function stripallslashes($string) {
    while(
strchr($string,'\\')) {
       
$string = stripslashes($string);
    }
}
?>

Hope it's usefull , O-Zone
up
0
Anonymous
4 years ago
Rather use str_replace than explode/implode for your purpose.
up
0
alex dot launi at gmail dot com
11 years ago
kibby: I modified the stripslashes_deep() function so that I could use it on NULL values.

function stripslashes_deep($value)
{
    if(isset($value)) {
        $value = is_array($value) ?
            array_map('stripslashes_deep', $value) :
            stripslashes($value);
    }
    return $value;
}
up
0
lukas.skowronski at gmail dot com
12 years ago
If You want to delete all slashes from any table try to use my function:

function no_slashes($array)
    {
        foreach($array as $key=>$value)
            {
                if(is_array($value))
                    {
                        $value=no_slashes($value);
                        $array_temp[$key]=$value;                       
                    }
                else
                    {
                        $array_temp[$key]=stripslashes($value);
                    }
            }       
        return $array_temp;   
    }
up
0
gregory at nutt dot ca
12 years ago
Here is code I use to clean the results from a MySQL query using the stripslashes function.

I do it by passing the sql result and the sql columns to the function strip_slashes_mysql_results.  This way, my data is already clean by the time I want to use it.

    function db_query($querystring, $array, $columns)
    {
      if (!$this->connect_to_mysql())
       return 0;

     $queryresult = mysql_query($querystring, $this->link)
        or die("Invalid query: " . mysql_error());
   
      if(mysql_num_rows($queryresult))
      {
          $columns = mysql_field_names ($queryresult);
   
          if($array)
          {
              while($row = mysql_fetch_row($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
          else
          {
              while($row = mysql_fetch_object($queryresult))
                $row_meta[] = $this->strip_slashes_mysql_results($row, $columns);
              return $row_meta;
          }
      }
      else
        return 0;
    }
   
    function strip_slashes_mysql_results($result, $columns)
    {
        foreach($columns as $column)
        {
              if($this->debug)
                  printp(sprintf("strip_slashes_mysql_results: %s",strip_slashes_mysql_results));
              $result->$column = stripslashes($result->$column);
        }
        return $result;
    }
up
0
stoic
12 years ago
in response to crab dot crab at gmail dot com:

$value need not be passed by reference. The 'stripped' value is returned. The passed value is not altered.
up
0
Anonymous
14 years ago
If you want to deal with slashes in double-byte encodings, such as shift_jis or big5, you may use this:

<?
function stripslashes2($string) {
    $string = str_replace("\\\"", "\"", $string);
    $string = str_replace("\\'", "'", $string);
    $string = str_replace("\\\\", "\\", $string);
    return $string;
}
?>
up
-1
Yousef Ismaeil Cliprz
6 years ago
If you want to use stripslashes(); function for a string or array you can create a user function

as in example:

<?php

if (!function_exists('strip_slashes'))
{
   
/**
     * Un-quotes a quoted string.
     *
     * @param (mixed) $str - The input string.
     * @author Yousef Ismaeil Cliprz
     */
   
function strip_slashes($str)
    {
        if (
is_array($str))
        {
            foreach (
$str as $key => $val)
            {
               
$str[$key] = strip_slashes($val);
            }
        }
        else
        {
           
$str = stripslashes($str);
        }

        return
$str;
    }
}

$arr = array('Yousef\\\'s','\"PHP.net\"','user\\\'s');

echo
'With strip_slashes() function:<br />';
print_r(strip_slashes($arr));
echo
'<br />';
echo
'Without strip_slashes() function:<br />';
print_r($arr);

/** You will get
With strip_slashes() function:
Array ( [0] => Yousef's [1] => "PHP.net" [2] => user's )
Without strip_slashes() function:
Array ( [0] => Yousef\'s [1] => \"PHP.net\" [2] => user\'s )
*/

?>
up
-1
tarmo at goyf dot de
7 years ago
When matching strings with approstrophes against the mysql database, my query kept failing while it worked fine when I copied the same query directly to perform the database query. After several hours I found that stripslashes() made the string longer and hence it wasn't "equal" for the query.

This code shows the behavior (copy into "test.php"). Replacing stripslashes worked for me.

<?php
echo '<h2>Post-Data</h2>';
var_dump($_POST);

$f1 = trim(filter_var(stripslashes($_POST[form]), FILTER_SANITIZE_STRING));
echo
'<h2>stripslashes</h2>';
var_dump($f1);

$f2 = trim(str_replace("|","'",filter_var(str_replace("\'","|",$_POST[form]), FILTER_SANITIZE_STRING)));
echo
'<h2>workaround</h2>';
var_dump($f2);
   
echo
'<form action="test.php" method="post">
    <input type="text" name="form">
    <input type="submit">
    </form>'
;
?>

Entering "foo'bar" creates this output:
// Post-Data
// array(1) { ["form"]=> string(8) "foo\'bar" }
// stripslashes
// string(11) "foo'bar"
// workaround
// string(7) "foo'bar"
up
-1
dragonfly at networkinsight dot net
12 years ago
If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.
up
-1
mattyblah at gmail dot com
14 years ago
It should be of note that if you are stripping slashes to get rid of the slashes added by magic_quotes_gpc then it will also remove slashes from \. This may not seem that bad but if you have someone enter text such as 'testing\' with a slash at the end, this will cause an error if not corrected. It's best to strip the slashes, then add a slash to every single slash using $text = str_replace('\\', '\\\\', $text);
up
-1
Tom Worster
10 years ago
A replacement that should be safe on utf-8 strings.
<?php
  preg_replace
(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
up
-2
jeremysawesome
8 years ago
I'm using this to clean the $_POST array:
<?php
array_walk_recursive
($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
up
-2
eugene at ultimatecms dot co dot za
9 years ago
This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

<?php

function no_magic_quotes($query) {
       
$data = explode("\\",$query);
       
$cleaned = implode("",$data);
        return
$cleaned;
}

// I'm using mysql_escape_string as a simple example, but this function would work for any escaped string.
$query = "It's amaizing! Who's to say this isn't a simple function?";
$badstring = mysql_escape_string($query);

echo
'<b>Without funtion:</b> '.$badstring;
echo
'<br><br>';
echo
'<b>With function:</b> '.no_magic_quotes($badstring);

?>

Output:
Without funtion: It\'s amaizing! Who\'s to say this isn\'t a simple function?

With function: It's amaizing! Who's to say this isn't a simple function?
up
-2
todd at toddzebert dot com
7 years ago
Attempting to use stripslashes on an array in 5.2.17 returns the string "Array", but in 5.3.6 it returns NULL.
up
-2
JAB Creations
12 years ago
When writing to a flatfile such as an HTML page you'll notice slashes being inserted. When you write to that page it's interesting how to apply stripslashes...

I replaced this line...
<?php fwrite($file, $_POST['textarea']); ?>

With...
<?php if (get_magic_quotes_gpc()) {fwrite ($file, stripslashes($_POST['textarea']));}?>

You have to directly apply stripslashes to $_POST, $_GET, $_REQUEST, and $_COOKIE.
up
-2
Aditya P Bhatt (adityabhai at gmail dot com)
11 years ago
Here is simple example code which you can use as a common function in your functions file:

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
    if(
get_magic_quotes_gpc()) {
        return
stripslashes($string);
    } else {
        return
$string;
    }
}
?>
up
-2
hash at samurai dot fm
15 years ago
Might I warn readers that they should be vary careful with the use of stripslashes on Japanese text. The shift_jis character set includes a number of two-byte code charcters that contain the hex-value 0x5c (backslash) which will get stripped by this function thus garbling those characters.

What a nightmare!
up
-2
JacobRas.nl
10 years ago
Hi,

Here's an function that strips not only \', but also \\' and \\\' and so on (depending on $times). $text = the text that needs to be stripped, $times = how much backslashes should be stripped.

<?php

function stripslashes_deep ($text, $times) {
   
   
$i = 0;
   
   
// loop will execute $times times.
   
while (strstr($text, '\\') && $i != $times) {
       
       
$text= stripslashes($text);
       
$i++;
       
    }
   
    return
$text;
   
}

?>

Example: $text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> will return 'quote'.
Note: <?php stripslashes_deep($text, 3); ?> will also return 'quote'.
up
-2
jeremycook0 at googlemail dot com
9 years ago
Here's a way of stripping slashes in PHP 5.3 using a recursive closure:

<?php
 
if (get_magic_quotes_gpc()) {
     
$strip_slashes_deep = function ($value) use (&$strip_slashes_deep) {
          return
is_array($value) ? array_map($strip_slashes_deep, $value) : stripslashes($value);
      };
     
$_GET = array_map($strip_slashes_deep, $_GET);
     
$_POST = array_map($strip_slashes_deep, $_POST);
     
$_COOKIE = array_map($strip_slashes_deep, $_COOKIE);
  }
?>

Note that the variable '$strip_slashes_deep' has to be passed to the closure by reference. I think that this is because at the time the closure is created the variable '$strip_slashes_deep' doesn't exist: the closure itself becomes the value of the variable. Passing by reference solves this issue. This closure could easily be adapted to use other methods of stripping slashes such as preg_replace().
up
-3
michal at roszka dot pl
9 years ago
The goal is to leave the input untouched in PHP 5.2.8. Let's have this sample text given in $_POST['example']:

a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Let's have two simple scripts:

Script A:
<?php echo $_POST['example']; ?>

Script B:
<?php echo stripslashes($_POST['example']); ?>

Let's have four different configurations and corresponding output:

Case #1:

* magic_quotes_gpc = Off
* magic_quotes_sybase = Off

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #2

* magic_quotes_gpc = On
* magic_quotes_sybase = Off

A: a backslash ( \\ ), a single-quote ( \' ), a double-quote ( \" ) and a null character ( \\0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )

Case #3

* magic_quotes_gpc = On
* magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( '' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Case #4

* magic_quotes_gpc = Off
* magic_quotes_sybase = On

A: a backslash ( \ ), a single-quote ( ' ), a double-quote ( " ) and a null character ( \0 )
B: a backslash (  ), a single-quote ( ' ), a double-quote ( " ) and a null character ( � )

Conclusions:

1) we do not need to do anything, if the magic_quotes_gpc is disabled (cases 1 and 4);
2) stripslashes($_POST['example']) only works, if the magic_quotes_gpc is enabled, but the magic_quotes_sybase is disabled (case 2);
3) str_replace("''", "'", $_POST['example']) will do the trick if both the magic_quotes_gpc and the magic_quotes_sybase are enabled (case 3);

<?php
function disable_magic_quotes_gpc()
{
    if (
TRUE == function_exists('get_magic_quotes_gpc') && 1 == get_magic_quotes_gpc())
    {
       
$mqs = strtolower(ini_get('magic_quotes_sybase'));

        if (
TRUE == empty($mqs) || 'off' == $mqs)
        {
           
// we need to do stripslashes on $_GET, $_POST and $_COOKIE
       
}
        else
        {
           
// we need to do str_replace("''", "'", ...) on $_GET, $_POST, $_COOKIE
       
}
    }
   
// otherwise we do not need to do anything
}
?>

Important notes:

1) arrays need to be processed recursively;

2) both stripslashes and str_replace functions always return strings, so:

* TRUE will become a string "1",
* FALSE will become an empty string,
* integers and floats will become strings,
* NULL will become an empty string.

On the other hand you only need to process strings, so use the is_string function to check;

3) when dealing with other (than GPC) data sources, such as databases or text files, remember to play with the magic_quotes_runtime setting as well, see, what happens and write a corresponding function, i.e. disable_magic_quotes_runtime() or something.

4) VERY IMPORTANT: when testing, remember the null character. Otherwise your tests will be inconclusive and you may end up with... well, serious bugs :)
up
-3
techdesk100
11 years ago
Function which checks if $input has correct slashes,
otherwise adds slashes. For cases when you are not sure the input is not already addslashed.

    public function addslashes_once($input){
        //These characters are single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).
        $pattern = array("\\'", "\\\"", "\\\\", "\\0");
        $replace = array("", "", "", "");
        if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
            return addslashes($input);
        }
        else{
            return $input;
        }
    }
up
-6
hauser dot j at gmail dot com
13 years ago
Don't use stripslashes if you depend on the values NULL.

Apparently stripslashes converts NULL to string(0) ""

<?php
$a
= null;
var_dump($a);

$b = stripslashes($a);
var_dump($b);
?>
Will output

NULL
string(0) ""
up
-3
powerofBBC at gmail dot com
8 months ago
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";

if( (strlen($_POST['query']) > 0) && (preg_match_all($regex_pattern, $_POST['query']) )
{ echo "Tags found"; }
up
-6
dragon[dot]dionysius[at]gmail[dot]com
10 years ago
I use this function in my class to stripslashes arrays including NULL-check:

<?php
   
private function stripslashes_deep($value) {
        if(
is_array($value)) {
            foreach(
$value as $k => $v) {
               
$return[$k] = $this->stripslashes_deep($v);
            }
        } elseif(isset(
$value)) {
           
$return = stripslashes($value);
        }
        return
$return;
    }
?>
up
-10
alf at mitose dot net
13 years ago
Take care using stripslashes() if the text you want to insert in the database contain \n characters ! You'll see "n" instead of (not seeing) "\n".

It should be no problem for XML, but is still boring ...
up
-9
Evgeny
11 years ago
extended version of stripslashes_deep. This allow to strip one also in the array_keys

    function stripslashes_deep($value) {
        if (is_array($value)) {
            if (count($value)>0) {
                $return = array_combine(array_map('stripslashes_deep', array_keys($value)),array_map('stripslashes_deep', array_values($value)));
            } else {
                $return = array_map('stripslashes_deep', $value);
            }
            return $return;
        } else {
            $return = stripslashes($value);
            return $return ;
        }
    }
To Top