`
yanyanquan
  • 浏览: 441071 次
  • 性别: Icon_minigender_1
  • 来自: 江门
社区版块
存档分类
最新评论

php中字符串转义函数

 
阅读更多

mysql_escape_string
(PHP 4 >= 4.0.3, PHP 5, PECL mysql:1.0)

mysql_escape_string — 转义一个字符串用于 mysql_query 

说明
string mysql_escape_string ( string $unescaped_string )
本函数将 unescaped_string 转义,使之可以安全用于 mysql_query()。 

Note: mysql_escape_string() 并不转义 % 和 _。 本函数和 mysql_real_escape_string() 完全一样,除了 mysql_real_escape_string() 接受的是一个连接句柄并根据当前字符集转移字符串之外。mysql_escape_string() 并不接受连接参数,也不管当前字符集设定。 
Example#1 mysql_escape_string() 例子
<?php
    $item = "Zak's Laptop";
    $escaped_item = mysql_escape_string($item);
    printf ("Escaped string: %s\n", $escaped_item);
?> 
以上例子将产生如下输出: 
Escaped string: Zak\'s Laptop

mysql_real_escape_string
(PHP 4 >= 4.3.0, PHP 5, PECL mysql:1.0)

mysql_real_escape_string — 转义 SQL 语句中使用的字符串中的特殊字符,并考虑到连接的当前字符集 

说明
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )
本函数将 unescaped_string 中的特殊字符转义,并计及连接的当前字符集,因此可以安全用于 mysql_query()。 

Note: mysql_real_escape_string() 并不转义 % 和 _。 


Example#1 mysql_real_escape_string() 例子

<?php
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?> 
以上例子将产生如下输出: 

Escaped string: Zak\'s and Derick\'s Laptop


addcslashes
(PHP 4, PHP 5)

addcslashes — 以 C 语言风格使用反斜线转义字符串中的字符

说明
string addcslashes ( string $str , string $charlist )
返回字符串,该字符串在属于参数 charlist 列表中的字符前都加上了反斜线。如果 charlist 中包含有 \n,\r 等字符,将以 C 语言风格转换,而其它非字母数字且 ASCII 码低于 32 以及高于 126 的字符均转换成使用八进制表示。 

当 选择对字符 0,a,b,f,n,r,t 和 v 进行转义时需要小心,它们将被转换成 \0,\a,\b,\f,\n,\r,\t 和 \v。在 PHP 中,只有 \0(NULL),\r(回车符),\n(换行符)和 \t(制表符)是预定义的转义序列, 而在 C 语言中,上述的所有转换后的字符都是预定义的转义序列。 

charlist 参数,如“\0..\37”,将转义所有 ASCII 码介于 0 和 31 之间的字符。 

Example#1 addcslashes() 例子

<?php
$escaped = addcslashes($not_escaped, "\0..\37!@\177..\377");
?> 

当定义 charlist 参数中的字符序列时,需要确实知道介于自己设置的开始及结束范围之内的都是些什么字符。 

<?php
echo addcslashes('foo[ ]', 'A..z');
// 输出:\f\o\o\[ \]
// 所有大小写字母均被转义
// ... 但 [\]^_` 以及分隔符、换行符、回车符等也一并被转义了。
?> 
另外,如果设置范围中的结束字符 ASCII 码高于开始字符,则不会创建范围,只是将开始字符、结束字符以及其间的字符逐个转义。可使用 ord() 函数获取字符的 ASCII 码值。 
<?php
echo addcslashes("zoo['.']", 'z..A');
// 输出:\zoo['\.']
?> 


addslashes
(PHP 4, PHP 5)

addslashes — 使用反斜线引用字符串

说明
string addslashes ( string $str )
返回字符串,该字符串为了数据库查询语句等的需要在某些字符前加上了反斜线。这些字符是单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)。 

一 个使用 addslashes() 的例子是当你要往数据库中输入数据时。例如,将名字 O'reilly 插入到数据库中,这就需要对其进行转义。大多数据库使用 \ 作为转义符:O\'reilly。这样可以将数据放入数据库中,而不会插入额外的 \。当 PHP 指令 magic_quotes_sybase 被设置成 on 时,意味着插入 ' 时将使用 ' 进行转义。 

默认情况 下,PHP 指令 magic_quotes_gpc 为 on,它主要是对所有的 GET、POST 和 COOKIE 数据自动运行 addslashes()。不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义。遇到这种情况时可以使用函数 get_magic_quotes_gpc() 进行检测。 


Example#1 addslashes() 例子

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

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


stripslashes
(PHP 4, PHP 5)

stripslashes — Un-quote string quoted with addslashes()

说明
string stripslashes ( string $str )
Un-quotes a quoted string. 

Note: If magic_quotes_sybase is on, no backslashes are stripped off but two apostrophes are replaced by one instead. 


An example use of stripslashes() is when the PHP directive magic_quotes_gpc is on (it's on by default), and 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. 

参数

str 
The input string. 


返回值
Returns a string with backslashes stripped off. (\' becomes ' and so on.) Double backslashes (\\) are made into a single backslash (\). 

范例

Example#1 A stripslashes() example

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

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

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

    return $value;
}

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

// Output
print_r($array);
?> 
上例将输出:

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

)

    
stripcslashes
(PHP 4, PHP 5)

stripcslashes — Un-quote string quoted with addcslashes()

说明
string stripcslashes ( string $str )
Returns a string with backslashes stripped off. Recognizes C-like \n, \r ..., octal and hexadecimal representation. 

参数

str 
The string to be unescaped. 


返回值
Returns the unescaped string. 

htmlspecialchars
(PHP 4, PHP 5)

htmlspecialchars — Convert special characters to HTML entities 

Description
string htmlspecialchars ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
Certain characters have special significance in HTML, and should be represented by HTML entities if they are to preserve their meanings. This function returns a string with some of these conversions made; the translations made are those most useful for everyday web programming. If you require all HTML character entities to be translated, use htmlentities() instead. 

This function is useful in preventing user-supplied text from containing HTML markup, such as in a message board or guest book application. The optional second argument, quote_style , tells the function what to do with single and double quote characters. The default mode, ENT_COMPAT, is the backwards compatible mode which only translates the double-quote character and leaves the single-quote untranslated. If ENT_QUOTES is set, both single and double quotes are translated and if ENT_NOQUOTES is set neither single nor double quotes are translated.

The translations performed are: 

'&' (ampersand) becomes '&' 
'"' (double quote) becomes '"' when ENT_NOQUOTES is not set. 
''' (single quote) becomes ''' only when ENT_QUOTES is set. 
'<' (less than) becomes '<' 
'>' (greater than) becomes '>' 
Example#1 htmlspecialchars() example

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new; // <a href='test'>Test</a>
?> 

Note that this function does not translate anything beyond what is listed above. For full entity translation, see htmlentities(). Support for the optional second argument was added in PHP 3.0.17 and PHP 4.0.3. 

The third argument charset defines character set used in conversion. The default character set is ISO-8859-1. Support for this third argument was added in PHP 4.1.0. 

PHP 4.3.0 及其后续版本支持如下字符集。 已支持字符集 字符集 别名 描述 
ISO-8859-1 ISO8859-1 西欧,Latin-1  
ISO-8859-15 ISO8859-15 西欧,Latin-9。增加了 Latin-1(ISO-8859-1)中缺少的欧元符号、法国及芬兰字母。  
UTF-8   ASCII 兼容多字节 8-bit Unicode。  
cp866 ibm866, 866 DOS-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。  
cp1251 Windows-1251, win-1251, 1251 Windows-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。  
cp1252 Windows-1252, 1252 Windows 对于西欧特有的字符集。  
KOI8-R koi8-ru, koi8r 俄文。PHP 4.3.2 开始支持该字符集。  
BIG5 950 繁体中文,主要用于中国台湾。  
GB2312 936 简体中文,国际标准字符集。  
BIG5-HKSCS   繁体中文,Big5 的延伸,主要用于香港。  
Shift_JIS SJIS, 932 日文。  
EUC-JP EUCJP 日文。  


Note: ISO-8859-1 将代替任何其它无法识别的字符集。 


When double_encode is turned off PHP will not encode existing html entities, the default is to convert everything. This parameter was added in PHP 5.2.3. 

See also get_html_translation_table(), htmlspecialchars_decode(), strip_tags(), htmlentities(), and nl2br(). 

htmlentities
(PHP 4, PHP 5)

htmlentities — Convert all applicable characters to HTML entities

说明
string htmlentities ( string $string [, int $quote_style [, string $charset [, bool $double_encode ]]] )
This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities. 

If you're wanting to decode instead (the reverse) you can use html_entity_decode(). 

参数

string 
The input string. 

quote_style 
Like htmlspecialchars(), the optional second quote_style parameter lets you define what will be done with 'single' and "double" quotes. It takes on one of three constants with the default being ENT_COMPAT: Available quote_style constants Constant Name Description 
ENT_COMPAT Will convert double-quotes and leave single-quotes alone. 
ENT_QUOTES Will convert both double and single quotes. 
ENT_NOQUOTES Will leave both double and single quotes unconverted. 


charset 
Like htmlspecialchars(), it takes an optional third argument charset which defines character set used in conversion. Presently, the ISO-8859-1 character set is used as the default. 

PHP 4.3.0 及其后续版本支持如下字符集。 已支持字符集 字符集 别名 描述 
ISO-8859-1 ISO8859-1 西欧,Latin-1  
ISO-8859-15 ISO8859-15 西欧,Latin-9。增加了 Latin-1(ISO-8859-1)中缺少的欧元符号、法国及芬兰字母。  
UTF-8   ASCII 兼容多字节 8-bit Unicode。  
cp866 ibm866, 866 DOS-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。  
cp1251 Windows-1251, win-1251, 1251 Windows-特有的 Cyrillic 字母字符集。PHP 4.3.2 开始支持该字符集。  
cp1252 Windows-1252, 1252 Windows 对于西欧特有的字符集。  
KOI8-R koi8-ru, koi8r 俄文。PHP 4.3.2 开始支持该字符集。  
BIG5 950 繁体中文,主要用于中国台湾。  
GB2312 936 简体中文,国际标准字符集。  
BIG5-HKSCS   繁体中文,Big5 的延伸,主要用于香港。  
Shift_JIS SJIS, 932 日文。  
EUC-JP EUCJP 日文。  


Note: ISO-8859-1 将代替任何其它无法识别的字符集。 


double_encode 
When double_encode is turned off PHP will not encode existing html entities. The default is to convert everything. 


返回值
Returns the encoded string. 

更新日志
版本 说明 
5.2.3 The double_encode parameter was added.  
4.1.0 The charset parameter was added.  
4.0.3 The quote_style parameter was added.  


范例

Example#1 A htmlentities() example

<?php
$str = "A 'quote' is <b>bold</b>";

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str);

// Outputs: A 'quote' is <b>bold</b>
echo htmlentities($str, ENT_QUOTES);
?> 

nl2br
(PHP 4, PHP 5)

nl2br — Inserts HTML line breaks before all newlines in a string

说明
string nl2br ( string $string )
Returns string with '<br />' inserted before all newlines. 

参数

string 
The input string. 


返回值
Returns the altered string. 

更新日志
版本 说明 
4.0.5 nl2br() is now XHTML compliant. All older versions will return string with '<br>' inserted before newlines instead of '<br />'.  


范例

Example#1 using nl2br()

<?php
echo nl2br("foo isn't\n bar");
?> 
上例将输出:

foo isn't<br />
bar


quotemeta
(PHP 4, PHP 5)

quotemeta — Quote meta characters

说明
string quotemeta ( string $str )
Returns a version of str with a backslash character (\) before every character that is among these: 

. \ + * ? [ ^ ] ( $ )
参数

str 
The input string. 


返回值
Returns the string with meta characters quoted. 

注释
Note: 本函数可安全用于二进制对象。


get_magic_quotes_gpc
(PHP 4, PHP 5)

get_magic_quotes_gpc — Gets the current configuration setting of magic quotes gpc

说明
int get_magic_quotes_gpc ( void )
Returns the current configuration setting of magic_quotes_gpc 

Keep in mind that the setting magic_quotes_gpc will not work at runtime. 

For more information about magic_quotes, see this security section. 

返回值
Returns 0 if magic quotes gpc are off, 1 otherwise. 

范例

Example#1 get_magic_quotes_gpc() example

<?php
echo get_magic_quotes_gpc();         // 1
echo $_POST['lastname'];             // O\'reilly
echo addslashes($_POST['lastname']); // O\\\'reilly

if (!get_magic_quotes_gpc()) {
    $lastname = addslashes($_POST['lastname']);
} else {
    $lastname = $_POST['lastname'];
}

echo $lastname; // O\'reilly
$sql = "Insert INTO lastnames (lastname) VALUES ('$lastname')";
?> 

注释
Note: If the directive magic_quotes_sybase is ON it will completely override magic_quotes_gpc. So even when get_magic_quotes_gpc() returns TRUE neither double quotes, backslashes or NUL's will be escaped. Only single quotes will be escaped. In this case they'll look like: '' 



strip_tags
(PHP 4, PHP 5)

strip_tags — Strip HTML and PHP tags from a string

说明
string strip_tags ( string $str [, string $allowable_tags ] )
This function tries to return a string with all HTML and PHP tags stripped from a given str . It uses the same tag stripping state machine as the fgetss() function. 

参数

str 
The input string. 

allowable_tags 
You can use the optional second parameter to specify tags which should not be stripped. 

Note: HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with allowable_tags . 



返回值
Returns the stripped string. 

更新日志
版本 说明 
5.0.0 strip_tags() is now binary safe  
4.3.0 HTML comments are now always stripped  
4.0.0 The allowable_tags parameter was added  


范例

Example#1 strip_tags() example

<?php
$text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>';
echo strip_tags($text);
echo "\n";

// Allow <p> and <a>
echo strip_tags($text, '<p><a>');
?> 
上例将输出:

Test paragraph. Other text
<p>Test paragraph.</p> <a href="#fragment">Other text</a>

分享到:
评论

相关推荐

    转义表单提交字符处理函数

    转义表单提交字符处理函数,可用于php或javascript的字符处理函数列表

    PHP字符转义相关函数小结(php下的转义字符串)

    文章中有不正确的或者说辞不清的地方,麻烦大家指出了~~~与PHP字符串转义相关的配置和函数如下: 1.magic_quotes_runtime 2.magic_quotes_gpc 3.addslashes()和stripslashes() 4.mysql_escape_string() 5....

    node-php-escape-shell:基于php shell元字符的转义函数

    基于php shell元字符的转义函数 安装 npm install php-escape-shell 描述 逃生者 php_escapeshellarg() 在字符串周围添加单引号并引用/转义任何现有的单引号,允许您将字符串直接传递给 shell 函数并将其视为单个...

    PHP中addslashes()和stripslashes()实现字符串转义和还原用法实例

    本文实例讲述了PHP中addslashes()和stripslashes()实现字符串转义和还原用法。分享给大家供大家参考,具体如下: PHP中addslashes() 函数返回在预定义字符之前添加反斜杠的字符串。 预定义字符是: 单引号(’) 双...

    PHP常见字符串处理函数用法示例【转换,转义,截取,比较,查找,反转,切割】

    主要介绍了PHP常见字符串处理函数用法,结合实例形式分析了php针对字符串的大小写转换、转义、截取、比较、查找、反转、切割等操作,需要的朋友可以参考下

    PHP5 字符串处理函数大全

    addcslashes — 为字符串里面的部分字符添加反斜线转义字符 addslashes — 用指定的方式对字符串里面的字符进行转义 bin2hex — 将二进制数据转换成十六进制表示 chop — rtrim() 的别名函数 chr — 返回一个字符的...

    php查找字符串中第一个非0的位置截取

    您可能感兴趣的文章:PHP常见字符串处理函数用法示例【转换,转义,截取,比较,查找,反转,切割】PHP入门教程之字符串处理技巧总结(转换,过滤,解析,查找,截取,替换等)php查找字符串出现次数的方法PHP 查找字符串常用函数...

    几个有用的php字符串过滤,转换函数代码

    //除去字符串中所有空格 ltrim();//除去字符串左边空格 htmlspecialchars();//转换’$’,'”‘,'&lt;‘,’&gt;’为相应的html实体 htmlentities();//转换所有html标记为相应的html实体 array explode(string separator,...

    PHP常用字符串函数用法实例总结

    本文实例总结了PHP常用字符串函数用法。分享给大家供大家参考,具体如下: 字符串函数 explore 使用一个字符串分割另一个字符串 结果为数组 &lt;?php $str = 'a,b,c,d'; $res = explode(',',$str); var_dump($res);...

    解析php获取字符串的编码格式的方法(函数)

    如果不清楚字符串的编码格式的话,就可以将这段字符这样检查:$encode = mb_detect_encoding($string, array... 您可能感兴趣的文章:php strstr查找字符串中是否包含某些字符的查找函数PHP字符转义相关函数小结(php下

    一步一步学习PHP(7) php 字符串相关应用

    1. 字符串的表现形式 在PHP中,字符串有三种表现形式:单引号,双引号,以及heredoc。 PHP手册建议,在一般情况下,尽量使用单引号的字符串。如果需要转义变量,才使用双引号的字符串。如果需要多行显示,才使用...

    PHP正则表达式基本函数 修饰符 元字符和需转义字符说明

    我在写小偷中用了大量的正则,所以在接下来的版本中要逐步减少正则的应用 在PHP正则表达式中需要转义的字符如下: $^*()+={}[]|/:&lt;&gt;.?'” 注意:perl风格中表达式要求以/开始和结尾,如:/food/ 表匹配字符 food ...

    php实现处理输入转义字符的代码

    先来个函数,是最近WordPress 3.6中刚刚引入的 /** * Add slashes to a string or array of strings. * * This should be used when preparing data for core API that expects slashed data. * This should ...

    php学习 字符串课件

    print 语法bool(布尔行)print(string agr)次函数输出字符串 如果成功返回1 失败返回0 列如传输中如果客户的浏览器突然挂掉 则会造成失败的情景 字符串处理函数 ltrim 语法格式:string ltrim(string str);...

    PHP 转义使用详解

    php中数据的魔法引用函数 magic_quotes_gpc 或 magic_quotes_runtime  设置为on时,为我们引用的数据碰到 单引号’ 和 双引号” 以及 反斜线\ 时自动加上反斜线,帮我们自动转译符号,确保数据操作的正确运行两者...

Global site tag (gtag.js) - Google Analytics