删除多个空格 - PHP 找不到空格


Remove multiple whitespaces - PHP doesn't find the spaces

我知道,有很多类似的问题,你会说,是重复的,但我找不到解决方案!我需要删除多个空格,只写一个空格。在我的代码中,我写了"REPLACE"而不是",只是为了澄清。这是我测试过的一些代码,但无法正常工作:

$string=$data['post_content'];
$filtered1=preg_replace("/[^'S'r'n]+/",'REPLACE',$string);
$filtered2=preg_replace("#[^'S'r'n]+#",'REPLACE',$string);
$filtered3=preg_replace("#[^'S'r'n][^'S'r'n]+#",'REPLACE',$string);
$filtered4=preg_replace('#[^'S'r'n][^'S'r'n]+#','REPLACE',$string);
$filtered5=preg_replace('#!'s+!#', 'REPLACE', $string);
$filtered6=preg_replace("/(?<='s)'x20|'x20(?='s)/", "REPLACE", $string);
$filtered7=preg_replace("/(['s])'1+/", "REPLACE", $string);
$filtered8=preg_replace("#[^'S'r'n][^'S'r'n]#",'REPLACE',$string);
$filtered9=preg_replace("'/'s+/'",'REPLACE',$string);
$testing1=str_replace("  ","REPLACE",$string);
$testing2=str_replace("'s",'REPLACE',$string);
$testing3=str_replace(array('  '),'REPLACE',$string);
$testing4=str_replace('  ',"REPLACE",$string);
$testing5=str_replace("  ","REPLACE",$string);
$testing6=str_replace(array("  "),'REPLACE',$string);
$testing7=str_replace(array("'s's"),'REPLACE',$string);

这是字符串测试:

这是一个测试 1 2 3 4 6 结束

结果是针对$filtered1$filtered2

thisREPLACEisREPLACEaREPLACEtestREPLACE1 REPLACE2 REPLACE3 REPLACE4 REPLACE6 REPLACEend。

对于所有其他,结果是:

这是一个测试 1 2 3 4 6 结束

就像PHP找不到空格一样,即使explode也没有找到双精度空格" "。我正在使用 PHP 5.5.1

来了用

preg_replace('/[^'S'r'n]{2,}/',' ',$string);将双空格转换为单个空格

在此处查看演示:http://regex101.com/r/sP7wH7/1

但我宁愿使用最简单的preg_replace('/ {2,}/',' ',$string);来完成这个

测试字符串具有不间断空格,这些空格不会被正则表达式模式中的's拾取。请改用这个:

preg_replace('/('s+)|('xA0+)/u', ' ', $string);

问题不在于正则表达式,问题在于修饰符,我使用了修饰符u感谢 Aurimas的回答。以下是可能的解决方案:

$filtered1=preg_replace("/[^'S'r'n]+/u",' ',$string);
$filtered2=preg_replace("#[^'S'r'n]+#u",' ',$string);
$filtered3=preg_replace("#[^'S'r'n][^'S'r'n]+#u",' ',$string);
$filtered10=preg_replace('/[^'S'r'n]{2,}/u',' ',$string);0
$filtered11=preg_replace('/'h+/u', ' ', $string);
$filtered16=preg_replace('/('xA0+)/u', ' ', $string);