Php как убрать экранирование кавычек

stripslashes

stripslashes() can be used if you aren’t inserting this data into a place (such as a database) that requires escaping. For example, if you’re simply outputting data straight from an HTML form.

Parameters

Return Values

Returns a string with backslashes stripped off. ( \’ becomes ‘ and so on.) Double backslashes ( \\ ) are made into a single backslash ( \ ).

Examples

Example #1 A stripslashes() example

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

Note:

stripslashes() is not recursive. If you want to apply this function to a multi-dimensional array, you need to use a recursive function.

Example #2 Using stripslashes() on an array

function stripslashes_deep ( $value )
$value = is_array ( $value ) ?
array_map ( ‘stripslashes_deep’ , $value ) :
stripslashes ( $value );

// Example
$array = array( «f\\’oo» , «b\\’ar» , array( «fo\\’o» , «b\\’ar» ));
$array = stripslashes_deep ( $array );

The above example will output:

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

See Also

  • addslashes() — Quote string with slashes
  • get_magic_quotes_gpc() — Gets the current configuration setting of magic_quotes_gpc

User Contributed Notes 31 notes

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»:

function removeslashes ( $string )
$string = implode ( «» , explode ( «\\» , $string ));
return stripslashes ( trim ( $string ));
>

$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.

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!

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 ) ;

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 ) ;

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;
>

Читайте также:  Php parse url php url host

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;
>

Here is simple example code which you can use as a common function in your functions file:

function stripslashes_if_gpc_magic_quotes ( $string ) if( get_magic_quotes_gpc ()) return stripslashes ( $string );
> else return $string ;
>
>
?>

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;
>

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;
>

if( (strlen($_POST[‘query’]) > 0) && (preg_match_all($regex_pattern, $_POST[‘query’]) )

If you need to remove all slashes from a string, here’s a quick hack:

function stripallslashes ( $string ) <
while( strchr ( $string , ‘\\’ )) <
$string = stripslashes ( $string );
>
>
?>

Hope it’s usefull , O-Zone

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.

Recursive stripslashes
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 );
>
?>

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.

echo ‘

Post-Data

‘ ;
var_dump ( $_POST );

$f1 = trim ( filter_var ( stripslashes ( $_POST [ form ]), FILTER_SANITIZE_STRING ));
echo ‘

stripslashes

‘ ;
var_dump ( $f1 );

$f2 = trim ( str_replace ( «|» , «‘» , filter_var ( str_replace ( «\'» , «|» , $_POST [ form ]), FILTER_SANITIZE_STRING )));
echo ‘

workaround

‘ ;
var_dump ( $f2 );

A replacement that should be safe on utf-8 strings.
preg_replace (array( ‘/\x5C(?!\x5C)/u’ , ‘/\x5C\x5C/u’ ), array( » , ‘\\’ ), $s );
?>

If you are having trouble with stripslashes() corrupting binary data, try using urlencode() and urldecode() instead.

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.

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.

Читайте также:  Factor analysis in python

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);

If you want to use stripslashes(); function for a string or array you can create a user function

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 );
>

$arr = array( ‘Yousef\\\’s’ , ‘\»PHP.net\»‘ , ‘user\\\’s’ );

echo ‘With strip_slashes() function:
‘ ;
print_r ( strip_slashes ( $arr ));
echo ‘
‘ ;
echo ‘Without strip_slashes() function:
‘ ;
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 )
*/

This is a simple function to remove the slashes added by functions such as magic_quotes_gpc and mysql_escape_string etc.

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 ‘Without funtion: ‘ . $badstring ;
echo ‘

‘ ;
echo ‘With function: ‘ . 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?

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:

* 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 ( � )

* 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 )

* 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 ( � )

Читайте также:  background-position

* 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 ( � )

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);

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 🙂

Источник

stripslashes

Замечание:

Если включена директива magic_quotes_sybase, вместо обратных слешей будут удаляться двойные одинарные кавычки.

Функцию stripslashes() можно использовать, например, если директива конфигурации magic_quotes_gpc имеет значение on (она была включена по умолчанию в версиях до PHP 5.4), и экранирование символов не требуется. Например, данные не вставляются в базу данных, а просто выводятся в браузер.

Список параметров

Возвращаемые значения

Возвращает строку с вырезанными обратными слешами. (\’ становится и т.п.) Двойные обратные слеши (\\) становятся одинарными (\).

Примеры

Пример #1 Пример использования stripslashes()

// выводит: Вас зовут O’reilly?
echo stripslashes ( $str );
?>

Замечание:

stripslashes() не рекурсивна. Если вы хотите применить ее к многомерному массиву, то вам необходимо использовать рекурсивную функцию.

Пример #2 Использование stripslashes() с массивом

function stripslashes_deep ( $value )
$value = is_array ( $value ) ?
array_map ( ‘stripslashes_deep’ , $value ) :
stripslashes ( $value );

// Пример
$array = array( «f\\’oo» , «b\\’ar» , array( «fo\\’o» , «b\\’ar» ));
$array = stripslashes_deep ( $array );

Результат выполнения данного примера:

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

Смотрите также

  • addslashes() — Экранирует строку с помощью слешей
  • get_magic_quotes_gpc() — Получение текущего значения настройки конфигурации magic_quotes_gpc

Источник

Оцените статью