【问题标题】:Replace multiple instances of PHP替换多个 PHP 实例
【发布时间】:2011-04-17 21:29:55
【问题描述】:

我只是想知道如何用 php 替换多个 - 的实例,

比如说我有

test----test---3

我可以做些什么来替换 - 的多个实例,只需 1 个,这样就可以了

test-test-3

谢谢:)

【问题讨论】:

    标签: php string replace preg-replace


    【解决方案1】:

    删除每个重复的字符:

    $string = 'test----test---3';
    echo preg_replace('{(.)\1+}','$1',$string);
    

    删除特定的重复字符:

    $string = 'test----test---3';
    echo eregi_replace("-{2,}", "-", $string);
    

    以“丑陋”的方式删除特定的重复字符:

    $string = 'test----test---3';
    echo implode('-',array_filter(explode('-',$string)));
    

    所有 sn-ps 的结果:

    test-test-3
    

    【讨论】:

    • 问题是我只想替换 - 而不是其他字符,有什么想法只替换 - 吗?
    【解决方案2】:

    嗯……

    function replaceDashes($str){
        while(strpos($str,'--')!==false)
            $str=str_replace('--','-',$str);
        return $str;
    }
    

    你可以让它“更快”被替换:

            $str=str_replace('--','-',$str);
    

    与:

            $str=str_replace(array('----','---','--'),'-',$str);
    

    【讨论】:

      【解决方案3】:

      由于eregi_replace和ereg_replace在PHP5中已经贬值,你也可以试试

      preg_replace("/-{2,}/", "-", $string);
      

      所以如果你运行

      preg_replace("/-{2,}/", "-", "--a--b---c----")
      

      它会返回

      -a-b-c-

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-06-08
        • 2014-03-01
        • 2016-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-10-23
        相关资源
        最近更新 更多