我知道,有很多类似的问题,你会说,是重复的,但我找不到解决方案! 我需要删除多个空格,只写一个空格。在我的代码中,我写了'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
答案 0 :(得分:1)
在这里 使用
preg_replace('/[^\S\r\n]{2,}/',' ',$string);
将双空格转换为单一空格
在此处查看演示:http://regex101.com/r/sP7wH7/1
但我宁愿使用最简单的preg_replace('/ {2,}/',' ',$string);
来完成此
答案 1 :(得分:1)
您的测试字符串具有不间断的空格,在您的正则表达式模式中\s
无法获取这些空格。请改用:
preg_replace('/(\s+)|(\xA0+)/u', ' ', $string);
答案 2 :(得分:0)
问题不在于RegEx,问题是修饰符,我使用修饰符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);