删除HTML和特殊字符

Reh*_*hmy 42 php

我想使用任何PHP函数或其他什么,以便我可以删除任何HTML代码和特殊字符,并给我只有字母数字输出

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

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

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

$clear = strip_tags($des); echo $clear;
Run Code Online (Sandbox Code Playgroud)

那有什么办法吗〜谢谢

Mez*_*Mez 130

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

// 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);
Run Code Online (Sandbox Code Playgroud)

或者,一气呵成

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

  • +1因为与你的答案竞争太难了. (7认同)
  • 将html_entities_decode更改为html_entity_decode (3认同)

Mat*_*ein 13

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

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

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

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

  • 为Matt +1,但你应该把`strip_tags($ des)`变成`strip_tags(html_entity_decode($ des))`或者你有可能以一些流浪的'amp`,`lt`,`gt`结束输出中等... (4认同)

Joã*_*ira 5

所有其他解决方案都是令人毛骨悚然的,因为它们来自于一个自以为是简单地认为英语是世界上唯一语言的人:)

所有这些解决方案都去除了ç或à等变音符号。

PHP文档中所述,完美的解决方案很简单:

$clear = strip_tags($des);
Run Code Online (Sandbox Code Playgroud)