欢迎访问宙启技术站
智能推送

如何使用PHP中的strip_tags()函数过滤HTML标签

发布时间:2023-07-25 09:38:48

在PHP中,可以使用strip_tags()函数来过滤HTML标签。strip_tags()函数可以从一个字符串中删除或过滤HTML和PHP标签。

strip_tags()函数的语法如下:

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

其中,$str参数是要处理的字符串,而$allowable_tags参数是一个可选参数,它允许指定要保留的标签。如果指定了该参数,则只有指定的标签会被保留,其它标签将被删除。如果省略了该参数,则会删除所有的HTML和PHP标签。

以下是一些使用strip_tags()函数的示例:

1. 删除字符串中的所有HTML标签:

$string = "<p>This is a paragraph with <strong>HTML tags</strong> and <a href='example.com'>links</a>.</p>";
$filtered_string = strip_tags($string);
echo $filtered_string;

以上代码将输出:

This is a paragraph with HTML tags and links.

2. 保留部分标签:

$string = "<p>This is a paragraph with <strong>HTML tags</strong> and <a href='example.com'>links</a>.</p>";
$filtered_string = strip_tags($string, "<a>");
echo $filtered_string;

以上代码将输出:

This is a paragraph with HTML tags and <a href='example.com'>links</a>.

3. 过滤用户输入:

$user_input = $_POST['input'];
$filtered_input = strip_tags($user_input);
echo $filtered_input;

以上代码从用户的输入中删除了所有HTML和PHP标签。

需要注意的是,在使用strip_tags()函数时,需要小心可能带来的安全风险。仅仅使用strip_tags()函数无法防止跨站脚本攻击(XSS),因此在显示用户输入之前,还需要进行进一步的过滤和验证。