替换在文本中隐藏的 字符

62
如何删除下面文字中的隐藏的 和空格,但是:
  • 保留UNICODE字符
  • 保留<br>标记

我已经测试过:

  • 我使用了 trim($string) => 没有起作用
  • 我使用了 str_replace('&nbsp;', '', $string) => 没有起作用
  • 我使用了一些正则表达式 => 没有起作用

            <br>تاريخ ورود: یکشنبه ۲۳ بهمن ماه ۱۳۹۰

更新:隐藏的图像谢谢


在你的正则表达式中使用 \s 来匹配空格。 - Ben Carey
我已经完成了,但只是单纯地改变了单词之间的空格。 仍然存在。 - Behnam
抱歉,您能将HTML代码以文本形式发布,这样我就可以复制了。 - Ben Carey
整个页面上的任何内容都对我无效... - igneosaur
上述问题的最终解决方案对我有效。即:$string = htmlentities($string, null, 'utf-8'); $string = str_replace(" ", "", $string); - Asadullah
4个回答

91

这个解决方案可行,我已经测试过了:

$string = htmlentities($content, null, 'utf-8');
$content = str_replace("&nbsp;", "", $string);
$content = html_entity_decode($content);

4
天啊,终于找到解决方案了!在搜索数小时后,非常感谢您。我遇到了 阻止我的tinymce文本良好换行的问题,所以我用真正的空格替换了它们:function b09_remove_forced_spaces($content) { $string = htmlentities($content, null, 'utf-8'); $content = str_replace(" ", " ", $string); $content = html_entity_decode($content); return $content; } add_filter("the_content", "b09_remove_forced_spaces", 9);(不好的是stackoverflow不允许在评论中使用代码块) - rassoh

39

没有测试过,但如果你使用类似这样的内容:

$string = preg_replace("/\s/",'',$string);

那应该会去除所有的空格。

更新

要去除所有的空格和 &nbsp; 引用,可以使用类似以下的代码:

$string = preg_replace("/\s|&nbsp;/",'',$string);

更新2

尝试这个:

$string = html_entity_decode($string);

$string = preg_replace("/\s/",'',$string);

echo $string;

忘了说了,重新转换 HTML 实体,所以在替换后添加这个:

htmlentities($string);

我无法测试它,但请尝试 preg_replace("/(\s)|(\&nbsp\;)/",'',$string); - Ben Carey
好的,我会进一步调查。 - Ben Carey
你能把一些HTML代码贴到你的问题中吗?这样我就可以处理它了。 - Ben Carey
2
@BalusC 的解决方案对我没有用,我采用了另一种不同的方法。 - Tapper
已测试,phpExcel导出方法中可以移除&nbsp;->setCellValue('L'.$i, preg_replace(array('/\s{2,}|&nbsp;/', '/[\t\n]/'), ' ', $row['plaintiff'])) - TARKUS
显示剩余3条评论

5
所有上述解决方案都有点起作用,直到一个人开始使用德语,其中包括这些字母:
ä &auml;

我使用以下代码来处理与此类似的其他问题:

$string = preg_replace ( "!\s++!u", ' ', $string );

更多细节请参见:PCRE(3)库函数手册

模式末尾的量词事实上成为所有权:由于它没有后跟子模式,因此不会在其上发生回溯。因此!\s+!u更短、高效且具有相同功能。 - Casimir et Hippolyte

3
这对我很有效。

preg_replace("/&nbsp;/",'',$string)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接