strip_tags

(PHP 4, PHP 5, PHP 7)

strip_tags从字符串中去除 HTML 和 PHP 标记

说明

strip_tags ( string $str [, string $allowable_tags ] ) : string

该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。它使用与函数 fgetss() 一样的机制去除标记。

参数

str

输入字符串。

allowable_tags

使用可选的第二个参数指定不被去除的字符列表。

Note:

HTML 注释和 PHP 标签也会被去除。这里是硬编码处理的,所以无法通过 allowable_tags 参数进行改变。

Note:

In PHP 5.3.4 and later, self-closing XHTML tags are ignored and only non-self-closing tags should be used in allowable_tags. For example, to allow both <br> and <br/>, you should use:

<?php
strip_tags
($input'<br>');
?>

返回值

返回处理后的字符串。

更新日志

版本 说明
5.3.4 strip_tags() ignores self-closing XHTML tags in allowable_tags.
5.0.0 strip_tags() 变为二进制安全的。

范例

Example #1 strip_tags() 范例

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

// 允许 <p> 和 <a>
echo strip_tags($text'<p><a>');
?>

以上例程会输出:

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

注释

Warning

由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数据被删除。

Warning

该函数不会修改 allowable_tags 参数中指定的允许标记的任何属性,包括 styleonmouseover 属性,用户可能会在提交的内容中恶意滥用这些属性,从而展示给其他用户。

Note:

输入 HTML 标签名字如果大于 1023 字节(bytes)将会被认为是无效的,无论 allowable_tags 参数是怎样的。

参见