从 PHP 中的字符串中删除 HTML 代码


Remove HTML codes from string in PHP

我想使用 REGEX 从字符串中删除所有 HTML 代码,例如" € á ...

字符串:"This is a string " € á &"

所需输出:This is a string

你可以试试

$str="This is a string " € á &";
$new_str = preg_replace("/&#?[a-z0-9]+;/i",'',$str);
echo $new_str;

我希望这可能有效

设计

& - starting with 
# - some HTML entities use the # sign 
?[a-z0-9] - followed by
;- ending with a semi-colon
i - case insensitive. 

如果您尝试完全删除实体(即:不解码它们),请尝试以下操作:

$string = 'This is a string " € á &';
$pattern = '/&([#0-9A-Za-z]+);/';
echo preg_replace($pattern, '', $string);
$str = preg_replace_callback('/&[^; ]+;/', function($matches){
    return html_entity_decode($matches[0], ENT_QUOTES) == $matches[0] ? $matches[0] : '';
}, $str);

这将起作用,但不会剥离€因为它不是HTML 4中的实体。 如果你有PHP 5.4,你可以使用标志ENT_QUOTES | ENT_HTML5让它在HTML5实体(如€)中正常工作。

preg_replace('#&[^;]+;#', '', "This is a string " € á &");

试试这个:

preg_replace('/[^'w'd's]*/', '', htmlspecialchars_decode($string));

尽管它可能会删除一些您不想删除的内容。您可能需要修改正则表达式。