PHP函数strip_tags()的使用方法及实例
strip_tags()函数是PHP中的一个内置函数,用于去除字符串中的HTML和PHP标签。它的使用方法如下:
1. 基本用法:
strip_tags(string $str, array|string|null $allowable_tags = null) : string
参数说明:
- $str: 要处理的字符串。
- $allowable_tags (可选): 允许保留的标签,可以是一个字符串或一个数组。
2. 实例:
下面是几个示例,演示了strip_tags()函数的使用方法:
2.1 删除字符串中的所有HTML和PHP标记:
$str = '<h1>Example</h1>';
$result = strip_tags($str);
echo $result;
// 输出:Example
2.2 保留指定的HTML标记:
$str = '<p>Welcome to <b>PHP</b> world.</p>';
$result = strip_tags($str, '<p><b>');
echo $result;
// 输出:<p>Welcome to <b>PHP</b> world.</p>
2.3 保留指定的HTML标记和属性:
$str = '<a href="https://example.com">Example</a>';
$result = strip_tags($str, '<a><a href>');
echo $result;
// 输出:<a href="https://example.com">Example</a>
2.4 删除字符串中的PHP标记:
$str = "PHP code: <?php echo 'hello world'; ?>";
$result = strip_tags($str, array('php'));
echo $result;
// 输出:PHP code: echo 'hello world';
总结:
strip_tags()函数可以帮助我们去除字符串中的HTML和PHP标记,保留纯文本内容。通过指定第二个参数,我们可以选择保留特定的HTML标记和属性。使用strip_tags()函数可以提高数据的安全性,避免潜在的安全漏洞。
