用str_replace删除多余的空格


Remove extra white space with str_replace

标题和代码几乎是不言自明的......

但只是为了澄清更多...

我想在$myString中的每个单词之间保持一个空格(并删除坏词)......

如果可能的话,我更喜欢保持单行...

$myString = 'There    will      be     no   extra    space       here !!!';
str_replace(array("bad words","another bad words","'s+"), '', $myString);

我期待得到:

There will be no extra space here !!!

谢谢!

试试这个

$myString =     preg_replace('/'s's*/', ' ',$myString);

观看演示直播

str_replace替换字符串的特定匹配项。 在您的情况下,您只需删除不需要替换的空格preg_replace因此最适合您的情况。

要删除所有不需要的空格,您只需这样做,

法典

<?php
$myString = 'There    will      be     no   extra    space       here !!!';
echo str_replace('/'s+/', ' ',$myString);
?>

str_replacepreg_replace都产生相同的结果。 你可以在这里看到

结果

There will be no extra space here !!!
print (preg_replace('/ +/', ' ', $myString));

我想你想要:

$myString = 'There    will      be     no   extra    space       here !!!';
str_replace(array("bad words","another bad words","'s's"), array("","", " "), $myString);

您可以在$replace参数中使用数组,该数组的索引元素会重新排列$search参数的索引元素。

mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )