php使用函数嵌套调用实现过滤字符串中的HTML标记
时间: 2024-05-11 08:13:40 浏览: 6
以下是一个使用函数嵌套调用实现过滤字符串中的HTML标记的示例代码:
```php
function filter_html_tags($str) {
// 定义需要过滤的HTML标记
$html_tags = array('<script>', '</script>', '<style>', '</style>', '<link>', '<meta>', '<iframe>', '</iframe>', '<object>', '</object>', '<embed>', '</embed>', '<applet>', '</applet>', '<frame>', '</frame>', '<frameset>', '</frameset>', '<html>', '</html>', '<head>', '</head>', '<body>', '</body>', '<title>', '</title>', '<base>', '<form>', '</form>', '<input>', '<textarea>', '</textarea>', '<button>', '</button>', '<select>', '</select>', '<option>', '<optgroup>', '</optgroup>', '<label>', '</label>', '<fieldset>', '</fieldset>', '<legend>', '</legend>', '<table>', '</table>', '<caption>', '</caption>', '<thead>', '</thead>', '<tbody>', '</tbody>', '<tfoot>', '</tfoot>', '<tr>', '</tr>', '<th>', '</th>', '<td>', '</td>');
// 定义过滤函数
function filter($str) {
global $html_tags;
$str = strip_tags($str, implode('', $html_tags)); // 过滤HTML标记
$str = preg_replace('/\s+/', ' ', $str); // 去除多余的空格
$str = trim($str); // 去除首尾空格
return $str;
}
// 判断$str是否为数组
if (is_array($str)) {
foreach ($str as $key => $value) {
$str[$key] = filter_html_tags($value); // 递归调用
}
} else {
$str = filter($str); // 调用过滤函数
}
return $str;
}
// 示例
$str = '<p><a href="https://www.example.com">Example</a></p>';
echo filter_html_tags($str); // 输出:Example
```