PHP Conference Japan 2024

stripslashes

(PHP 4, PHP 5, PHP 7, PHP 8)

stripslashes移除已加引號的字串的引號

描述

stripslashes(字串 $string): 字串

移除已加引號的字串的引號。

如果您不是將此資料插入需要跳脫字元的地方(例如資料庫),可以使用 stripslashes()。例如,如果您只是直接輸出 HTML 表單中的資料。

參數

字串

輸入字串。

回傳值

回傳已移除反斜線的字串。(\' 會變成 ' 等等。)雙反斜線(\\)會變成單一反斜線(\)。

範例

範例 1 stripslashes() 範例

<?php
$str
= "你的名字是 O\'reilly 嗎?";

// 輸出:你的名字是 O'reilly 嗎?
echo stripslashes($str);
?>

注意:

stripslashes() 不是遞迴的。如果您想將此函式套用到多維陣列,您需要使用遞迴函式。

範例 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
        )

)

參見

新增註解

使用者貢獻的註解 30 筆註解

71
ivijan dot stefan at gmail dot com
10 年前
有時基於某些原因,PHP 或 Javascript 或某些惡意的程式碼會插入大量的反斜線。一般的函式不會注意到這一點。因此,需要將它「膨脹」一點。

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

/* 範例 */

$text="我的狗不\\\\\\\\\\\\\\\\'喜歡郵差!";
echo
removeslashes($text);
?>

結果:我的狗不喜歡郵差!

這個小技巧對我很有用,因為我之前遇到過這個問題。
6
shredder at technodrome dot com
15 年前
嗨,

這裡有一些遞迴的 addslashes / stripslashes 函式。
給定一個字串 - 它會簡單地加入/移除反斜線
給定一個陣列 - 它會遞迴地加入/移除陣列及其所有子陣列的反斜線。
如果該值不是字串或陣列 - 它將保持不修改!

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

?>
1
tarmo at goyf dot de
12 年前
當將含有單引號的字串與 mysql 資料庫比對時,我的查詢一直失敗,但當我直接複製相同的查詢來執行資料庫查詢時,卻運作良好。經過幾個小時,我發現 stripslashes() 使字串變長,因此查詢時並不「相等」。

這段程式碼顯示了這個行為(複製到 "test.php")。替換 stripslashes 對我來說有效。

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

輸入 "foo'bar" 會產生以下輸出
// Post-Data
// array(1) { ["form"]=> string(8) "foo\'bar" }
// stripslashes
// string(11) "foo'bar"
// workaround
// string(7) "foo'bar"
1
jeremycook0 at googlemail dot com
14 年前
這是一種在 PHP 5.3 中使用遞迴閉包來移除反斜線的方法

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

請注意,變數 '$strip_slashes_deep' 必須以參考方式傳遞到閉包中。我認為這是因為在建立閉包時,變數 '$strip_slashes_deep' 尚不存在:閉包本身會變成變數的值。以參考方式傳遞可以解決這個問題。這個閉包可以很容易地修改為使用其他移除反斜線的方法,例如 preg_replace()。
1
Tom Worster
15 年前
一個在 utf-8 字串上應該是安全的替換方法。
<?php
preg_replace
(array('/\x5C(?!\x5C)/u', '/\x5C\x5C/u'), array('','\\'), $s);
?>
1
Anonymous
10 年前
針對您的目的,請使用 str_replace 而不是 explode/implode。
2
o-zone at zerozone dot it
15 年前
如果您需要從字串中移除所有反斜線,這裡有一個快速的技巧

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

希望這對您有用,O-Zone
1
stoic
17 年前
回應 crab dot crab at gmail dot com

$value 不需要以參考方式傳遞。會回傳「已移除反斜線」的值。傳遞的值不會被更改。
1
eugene at ultimatecms dot co dot za
15 年前
這是一個簡單的函式,用於移除由 magic_quotes_gpc 和 mysql_escape_string 等函式新增的反斜線。

<?php

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

// 我使用 mysql_escape_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);

?>

輸出
沒有函式:It\'s amaizing! Who\'s to say this isn\'t a simple function?

使用函式:It's amaizing! Who's to say this isn't a simple function?
1
Aditya P Bhatt (adityabhai at gmail dot com)
16 年前
這裡有一個簡單的範例程式碼,您可以在您的函式檔案中將其用作通用函式

<?php
function stripslashes_if_gpc_magic_quotes( $string ) {
if(
get_magic_quotes_gpc()) {
return
stripslashes($string);
} else {
return
$string;
}
}
?>
1
dragonfly at networkinsight dot net
17 年前
如果您在使用 stripslashes() 時遇到損壞二進制資料的問題,請嘗試改用 urlencode() 和 urldecode()。
1
JAB Creations
17 年前
當寫入到 HTML 頁面等平面檔案時,您會注意到插入了斜線。當您寫入該頁面時,如何套用 stripslashes 會很有趣...

我將這一行替換為...
<?php fwrite($file, $_POST['textarea']); ?>

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

您必須直接將 stripslashes 套用到 $_POST、$_GET、$_REQUEST 和 $_COOKIE。
1
StefanoAI
11 年前
遞迴的 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);
}
?>
0
powerofBBC at gmail dot com
5 年前
$regex_pattern = "/<a href=\"(.*)\">(.*)<\/a>/";

if( (strlen($_POST['query']) > 0) && (preg_match_all($regex_pattern, $_POST['query']) )
{ echo "找到標籤"; }
1
gregory at nutt dot ca
17 年前
這是我用來使用 stripslashes 函式清理 MySQL 查詢結果的程式碼。

我透過將 SQL 結果和 SQL 資料行傳遞給函式 strip_slashes_mysql_results 來完成此操作。這樣,當我想要使用我的資料時,它已經是乾淨的了。

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

$queryresult = mysql_query($querystring, $this->link)
or die("無效的查詢:" . 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;
}
1
hash at samurai dot fm
21 年前
我想警告讀者,他們應該小心使用 stripslashes 處理日文文本。shift_jis 字元集包含許多雙位元組程式碼字元,這些字元包含十六進制值 0x5c(反斜線),這些字元會被此函式移除,從而破壞這些字元。

真是場噩夢!
0
todd at toddzebert dot com
12 年前
在 5.2.17 版本中,嘗試對陣列使用 stripslashes 會回傳字串 "Array",但在 5.3.6 版本中則會回傳 NULL。
0
michal at roszka dot pl
15 年前
目標是在 PHP 5.2.8 中保持輸入不變。假設在 $_POST['example'] 中有以下範例文字:

一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( \0 )

我們有兩個簡單的腳本

腳本 A
<?php echo $_POST['example']; ?>

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

我們有四種不同的配置和對應的輸出

案例 #1

* magic_quotes_gpc = Off
* magic_quotes_sybase = Off

A:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( \0 )
B:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( � )

案例 #2

* magic_quotes_gpc = On
* magic_quotes_sybase = Off

A:一個反斜線 ( \\ )、一個單引號 ( \' )、一個雙引號 ( \" ) 和一個空字元 ( \\0 )
B:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( \0 )

案例 #3

* magic_quotes_gpc = On
* magic_quotes_sybase = On

A:一個反斜線 ( \ )、一個單引號 ( '' )、一個雙引號 ( " ) 和一個空字元 ( \0 )
B:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( � )

案例 #4

* magic_quotes_gpc = Off
* magic_quotes_sybase = On

A:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( \0 )
B:一個反斜線 ( \ )、一個單引號 ( ' )、一個雙引號 ( " ) 和一個空字元 ( � )

結論

1) 如果 magic_quotes_gpc 被停用(案例 1 和 4),我們不需要做任何事;
2) 只有在 magic_quotes_gpc 啟用,但 magic_quotes_sybase 停用時(案例 2),stripslashes($_POST['example']) 才能正常運作;
3) 如果 magic_quotes_gpc 和 magic_quotes_sybase 都啟用時(案例 3),str_replace("''", "'", $_POST['example']) 會有效;

<?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)
{
// 我們需要對 $_GET、$_POST 和 $_COOKIE 執行 stripslashes
}
else
{
// 我們需要對 $_GET、$_POST、$_COOKIE 執行 str_replace("''", "'", ...)
}
}
// 否則我們不需要做任何事
}
?>

重要注意事項

1) 需要遞迴處理陣列;

2) stripslashes 和 str_replace 函式總是回傳字串,所以

* TRUE 會變成字串 "1",
* FALSE 會變成空字串,
* 整數和浮點數會變成字串,
* NULL 會變成空字串。

另一方面,你只需要處理字串,所以使用 is_string 函式來檢查;

3) 當處理其他(而非 GPC)資料來源時,例如資料庫或文字檔案,請記得同時調整 magic_quotes_runtime 設定,看看會發生什麼,並寫一個對應的函式,例如 disable_magic_quotes_runtime() 或類似的函式。

4) 非常重要:測試時,請記得空字元。否則你的測試會沒有結論,你可能會遇到...嚴重的錯誤 :)
0
alex dot launi at gmail dot com
16 年前
kibby:我修改了 stripslashes_deep() 函式,以便我可以在 NULL 值上使用它。

function stripslashes_deep($value)
{
if(isset($value)) {
$value = is_array($value) ?
array_map('stripslashes_deep', $value)
stripslashes($value);
}
return $value;
}
0
lukas.skowronski at gmail dot com
17 年前
如果你想從任何表格中刪除所有斜線,請嘗試使用我的函式

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;
}
0
Kibby
18 年前
好的,如果使用 stripslashes_deep,它肯定會將任何 NULL 替換為 ""。這會影響到依賴 isset() 的程式碼。請根據最近的說明提供解決方案。
0
mattyblah at gmail dot com
20 年前
應該注意的是,如果你正在剝除斜線以去除 magic_quotes_gpc 添加的斜線,它也會從 \ 中移除斜線。這看起來可能沒那麼糟,但如果有人輸入像 'testing\' 這樣以斜線結尾的文字,如果沒有修正,這會造成錯誤。最好是先剝除斜線,然後使用 $text = str_replace('\\', '\\\\', $text); 在每個斜線前加入一個斜線。
-1
Yousef Ismaeil Cliprz
11 年前
如果你想對字串或陣列使用 stripslashes(); 函式,你可以建立一個使用者函式

如下例所示

<?php

if (!function_exists('strip_slashes'))
{
/**
* 解除引用已引用的字串。
*
* @param (mixed) $str - 輸入字串。
* @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);

/** 你將得到
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 )
*/

?>
-1
JacobRas.nl
15 年前
嗨,

這是一個不僅會剝除 \',還會剝除 \\' 和 \\\' 等等(取決於 $times)的函式。$text = 需要剝除的文字,$times = 應該剝除多少個反斜線。

<?php

function stripslashes_deep ($text, $times) {

$i = 0;

// 迴圈將執行 $times 次。
while (strstr($text, '\\') && $i != $times) {

$text= stripslashes($text);
$i++;

}

return
$text;

}

?>

範例:$text = \\'quote\\' . <?php stripslashes_deep($text, 2); ?> 會回傳 'quote'。
注意: <?php stripslashes_deep($text, 3); ?> 也會回傳 'quote'。
-1
Anonymous
19 年前
如果你想處理雙位元組編碼中的斜線,例如 shift_jis 或 big5,你可以使用這個

<?
function stripslashes2($string) {
$string = str_replace("\\\"", "\"", $string);
$string = str_replace("\\'", "'", $string);
$string = str_replace("\\\\", "\\", $string);
return $string;
}
?>
-1
techdesk100
16 年前
檢查 $input 是否有正確斜線的函式,
否則會加入斜線。用於你不確定輸入是否已經使用 addslashes 的情況。

public function addslashes_once($input){
//這些字元是單引號 (')、雙引號 (")、反斜線 (\) 和 NUL(NULL 位元組)。
$pattern = array("\\'", "\\\"", "\\\\", "\\0");
$replace = array("", "", "", "");
if(preg_match("/[\\\\'\"\\0]/", str_replace($pattern, $replace, $input))){
return addslashes($input);
}
else{
return $input;
}
}
-3
jeremysawesome
13 年前
我正在使用這個來清理 $_POST 陣列
<?php
array_walk_recursive
($_POST, create_function('&$val', '$val = stripslashes($val);'));
?>
-4
hauser dot j at gmail dot com
18 年前
如果你依賴 NULL 值,請不要使用 stripslashes。

顯然 stripslashes 會將 NULL 轉換為 string(0) ""

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

$b = stripslashes($a);
var_dump($b);
?>
輸出結果

NULL
string(0) ""
-3
dragon[dot]dionysius[at]gmail[dot]com
15 年前
我在我的類別中使用此函式來移除陣列的反斜線,包含 NULL 檢查。

<?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;
}
?>
-5
alf at mitose dot net
19 年前
如果你想要插入資料庫的文字包含 \n 字元,請小心使用 stripslashes()!你會看到 "n" 而不是(看不到) "\n"。

這對 XML 來說應該沒問題,但仍然很煩人...
To Top