如何从 UTF-8 字符串中删除?

How to remove   from a UTF-8 string?

我的数据库正在返回一些字符串,例如:

This is a string

当字符串足够长并且您设置了最大宽度时会出现问题:

<p style="width:50px">This&nbsp;is&nbsp;a&nbsp;string</p>

为了驾驭 &nbsp; 个实体,我尝试使用以下过滤器但没有成功:

$new = preg_replace("/&nbsp;/i", " ", $str);
$new = str_replace('&nbsp;', ' ', $str);
$new = html_entity_decode($str);

您有一个 PHP fiddle to see this in action(我不得不从数据库输出中将字符串编码为十六进制;抱歉,该字符串是西班牙语)。

如何处理?为什么 html_entity_decode() 不起作用?那么替换功能呢?谢谢。

这很棘手,它不像替换普通字符串那样简单。

试试这个。

 str_replace("\xc2\xa0",' ',$str); 

或者这个,以上应该有效:

$nbsp = html_entity_decode("&nbsp;");
$s = html_entity_decode("[&nbsp;]");
$s = str_replace($nbsp, " ", $s);
echo $s;

@ref: https://moovwebconfluence.atlassian.net/wiki/pages/viewpage.action?pageId=1081435

获取 html 实体替换您想要的实体并解码回来:

$str = str_replace('&nbsp;', ' ', htmlentities($new));
$new = html_entity_decode($str);