【问题标题】:Remove extra space at the end of string using preg_replace使用 preg_replace 删除字符串末尾的多余空格
【发布时间】:2011-01-24 21:12:00
【问题描述】:

我想在 PHP 中使用 preg_replace 将字符串末尾的多余空格替换为空。我正在创建一个大的单词数据库,不知何故,最后有几个单词得到了额外的空白。

【问题讨论】:

    标签: php preg-replace


    【解决方案1】:

    您应该改用rtrim。它将删除字符串末尾的多余空格,并且比使用 preg_replace 更快。

    $str = "This is a string.    ";
    echo rtrim($str);
    

    速度比较 - preg_replacetrim

    // Our string
    $test = 'TestString    ';
    
    // Test preg_replace
    $startpreg = microtime(true);
    $preg = preg_replace("/^\s+|\s+$/", "", $test);
    $endpreg = microtime(true);
    
    // Test trim
    $starttrim = microtime(true);
    $trim = rtrim($test);
    $endtrim = microtime(true);
    
    // Calculate times
    $pregtime = $endpreg - $startpreg;
    $trimtime = $endtrim - $starttrim;
    
    // Display results
    printf("preg_replace: %f<br/>", $pregtime);
    printf("rtrim: %f<br/>", $trimtime);
    

    结果

    preg_replace:0.000036
    rtrim:0.000004

    如您所见,rtrim 实际上比nine times 更快。

    【讨论】:

      【解决方案2】:

      为什么不直接使用 trim() http://php.net/manual/en/function.trim.php

      【讨论】:

      • 我为什么没想到。谢谢你们俩
      • @Matthew 实际上,这是不正确的。 trim 往往比 preg_replace 快​​。作为一般经验法则,您应该在使用 RegEx 之前使用内置的 PHP 函数。
      • @MichaelIrigoyen 是的,对不起,我的错,由于某种原因,我把它们弄错了! maettig.com/code/php/php-performance-benchmarks.php
      【解决方案3】:

      根据需要使用 preg_replace :

      $s = ' okoki efef ef ef   
      ';
      
      print('-'.$s.'-<br/>');
      
      $s = preg_replace('/\s+$/m', '', $s);
      
      print('-'.$s.'-');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-10
        • 1970-01-01
        • 2023-01-04
        • 1970-01-01
        • 1970-01-01
        • 2012-08-19
        • 1970-01-01
        • 2011-08-05
        相关资源
        最近更新 更多