使用preg_replace删除空格在php中输出无法识别的字符[duplicate]

问题描述 投票:0回答:1

我想用一个空格替换多个空格或 ,所以我尝试使用preg_replace函数下面的代码,

所以它正确地替换了空格,但它也在输出字符串中放入了无法识别的字符,

对于演示我正在使用$string变量,但实际上它可以是来自服务器端数据库的数据,请参阅下面的代码:

<?php 
     $string = "123080345&nbsp;900113760  165604100012";
     echo preg_replace("/(\s|&nbsp;)+/",' ',$string);

     //output: 123080345� 900113760� 165604100012
     //expected output: 123080345 900113760 165604100012

所以我的问题是为什么preg_replace放置无法识别的字符以及如何获得干净和清晰的输出,

它没有无法识别的字符,因为我在上面的代码中显示为预期的输出

php regex string preg-replace pcre
1个回答
0
投票

虽然它只是数字串,spaces&nbsp;

但我认为在数据库中它是UTF-8编码的字符串所以当我尝试preg_replace它返回无法识别的字符。

所以当我用/uunicode标识符尝试相同的正则表达式时,它正在工作

以下是我的解决方案:

<?php 

     $string = "123080345&nbsp;900113760  165604100012";
     echo preg_replace("/(\s|&nbsp;)+/u",' ',$string); //u for unicode characters 

     //output: 123080345 900113760 165604100012

我希望它对某人有所帮助,谢谢。

© www.soinside.com 2019 - 2024. All rights reserved.