【问题标题】:Replace each leading and trailing whitespace with underscore using regex in php在php中使用正则表达式将每个前导和尾随空格替换为下划线
【发布时间】:2012-09-05 06:28:28
【问题描述】:
$string = "   Some string  ";
//the output should look like this
$output = "___Some string__";

所以每个前导和尾随空格都替换为下划线。

我在这里找到了 C 中的正则表达式:Replace only leading and trailing whitespace with underscore using regex in c# 但我无法让它在 php 中工作。

【问题讨论】:

    标签: php regex preg-replace whitespace


    【解决方案1】:

    您可以使用如下替换:

    $output = preg_replace('/\G\s|\s(?=\s*$)/', '_', $string);
    

    \G 匹配字符串的开头或上一个匹配的结尾,(?=\s*$) 匹配如果以下仅是字符串末尾的空格。 所以这个表达式匹配每个空格并将它们替换为_

    【讨论】:

    • @RazvanO。这与正则表达式无关,因此正则表达式有点棘手。 :-)
    • 不错的一个!即使那些其他解决方案确实有效,这也是我会在 .NET 和 PHP 中使用的解决方案。
    【解决方案2】:

    您可以按照 Qtax 的建议将正则表达式与前瞻一起使用。 使用 preg_replace_callback 的替代解决方案是: http://codepad.org/M5BpyU6k

    <?php
    $string = " Some string       ";
    $output = preg_replace_callback("/^\s+|\s+$/","uScores",$string); /* Match leading
                                                                         or trailing whitespace */
    echo $output;
    
    function uScores($matches)
    {
      return str_repeat("_",strlen($matches[0]));  /* replace matches with underscore string of same length */
    }
    ?>
    

    【讨论】:

      【解决方案3】:

      这段代码应该可以工作。如果没有,请告诉我。

      <?php 
      $testString ="    Some test   ";
      
      echo $testString.'<br/>';
      for($i=0; $i < strlen($testString); ++$i){
        if($testString[$i]!=" ")
          break;
        else
          $testString[$i]="_";
      }
      $j=strlen($testString)-1;
      for(; $j >=0; $j--){
        if($testString[$j]!=" ")
          break;
        else
          $testString[$j]="_";
      }
      
      echo $testString;
      
      ?>
      

      【讨论】:

        猜你喜欢
        • 2013-08-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-18
        • 1970-01-01
        • 2015-11-27
        • 1970-01-01
        相关资源
        最近更新 更多