【问题标题】:Remove extra white space with str_replace使用 str_replace 删除多余的空格
【发布时间】:2015-02-09 16:18:52
【问题描述】:

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

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

我想在$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 !!!

谢谢!

【问题讨论】:

    标签: php arrays string str-replace space


    【解决方案1】:

    试试这个

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

    【讨论】:

    • 是的,我知道这个技巧,但我想知道是否可以在里面做:str_replace(array("bad words","another bad words","\s+{2}"), ' ', $myString);
    【解决方案2】:

    查看演示Live

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

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

    代码

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

    str_replacepreg_replace 都产生相同的结果。你可以在 here

    上看到

    结果

    There will be no extra space here !!!
    

    【讨论】:

    • 是的,我知道这个技巧,但我想知道是否可以在 str_replace 中执行它(不使用另一条额外的行)...
    【解决方案3】:
    print (preg_replace('/ +/', ' ', $myString));
    

    【讨论】:

    • 是的,我知道这个技巧,但我想知道是否可以在 str_replace 中执行它(不使用另一条额外的行)...
    【解决方案4】:

    我想你想要:

    $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 ] )
    

    【讨论】:

      猜你喜欢
      • 2014-09-24
      • 2012-01-24
      • 2019-03-03
      • 1970-01-01
      • 2016-05-19
      • 1970-01-01
      • 2023-01-16
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多