去掉 HTML 和特殊字符

php
2022-08-30 10:40:43

我想使用任何php函数或任何东西,这样我就可以删除任何HTML代码和特殊字符,只给我字母数字输出

$des = "Hello world)<b> (*&^%$#@! it's me: and; love you.<p>";

我希望输出成为(只是Aa-Zz-0-9-WhiteSpace)Hello world it s me and love you

我试过,但它只删除了HTML代码strip_tags

$clear = strip_tags($des); 
echo $clear;

那么有什么办法可以做到这一点吗?


答案 1

对于正则表达式替换来说,这里可能更好

// Strip HTML Tags
$clear = strip_tags($des);
// Clean up things like &amp;
$clear = html_entity_decode($clear);
// Strip out any url-encoded stuff
$clear = urldecode($clear);
// Replace non-AlNum characters with space
$clear = preg_replace('/[^A-Za-z0-9]/', ' ', $clear);
// Replace Multiple spaces with single space
$clear = preg_replace('/ +/', ' ', $clear);
// Trim the string of leading/trailing space
$clear = trim($clear);

或者,一次性

$clear = trim(preg_replace('/ +/', ' ', preg_replace('/[^A-Za-z0-9 ]/', ' ', urldecode(html_entity_decode(strip_tags($des))))));

答案 2

去掉标签,只留下字母数字字符和空格:

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags($des));

编辑:所有功劳都归功于DaveRandom的完美解决方案...

$clear = preg_replace('/[^a-zA-Z0-9\s]/', '', strip_tags(html_entity_decode($des)));

推荐