腾讯云618限量抢购
  1. PHP+MySQL数据库教程
  2. PHP进阶教程
  3. ThinkPHP 3.0/3.1 教程

PHP 字符串存储(转义) addslashes 与 stripslashes 函数

最后更新:2010-10-19 19:08阅读:43746

PHP 字符串存储(转义)

PHP 的字符串向数据库进行写入时,为避免数据库错误,需要对特殊字符进行转义(字符前加上 符号)。如 O'reilly 转义成 O'reilly,这样可以将数据放入数据库中,而不会插入额外的 。

这些特殊字符包括:单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。

addslashes()

addslashes() 函数用于对特殊字符加上转义字符,返回一个字符串。

语法:

string addslashes ( string string )

例子:

<?php
$str = "Is your name O'reilly?";
echo addslashes($str);		// 输出:Is your name O\'reilly?
?>

提示

默认情况下,PHP 指令 magic_quotes_gpc 为 on,系统会对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes() 。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes() ,因为这样会导致双层转义。

可以对 get_magic_quotes_gpc() 进行检测以便确定是否需要使用 addslashes() :

<?php
if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}
echo $lastname;			//转义后的字符如:O'reilly
?>

stripslashes()

该函数为 addslashes() 的反函数,返回一个字符串。

语法:

string stripslashes ( string string )

例子:

<?php
$str = "Is your name O\'reilly?";
echo stripslashes($str);	// 输出:Is your name O'reilly?
?>

本章节内容共分 10 部分:
  1. 1. PHP 字符串输出 echo、print 与 printf 函数
  2. 2. PHP 字符串去除 trim、ltrim 与 rtrim 函数
  3. 3. PHP implode 函数:将数组元素组合为字符串
  4. 4. PHP 字符串获取 substr 与 strstr 函数
  5. 5. PHP 字符串计算 strlen、strpos 与 strrpos 函数
  6. 6. PHP 字符串 XHTML格式化显示 nl2br 与 htmlspecialchars 函数
  7. 7. PHP 字符串存储(转义) addslashes 与 stripslashes 函数
  8. 8. PHP 字符串分割 explode 与 str_split 函数
  9. 9. PHP 字符串替换 substr_replace 与 str_replace 函数
  10. 10. PHP 字符串处理
腾讯云618限量抢购