【问题标题】:Strlen to strip every [x] charactersStrlen 剥离每个 [x] 个字符
【发布时间】:2011-04-29 05:32:11
【问题描述】:

我正在尝试删除以下每三个字符(在示例中为句点)是我最好的猜测,并且与我得到的结果接近,但我错过了一些东西,可能是次要的。这种方法(如果我可以让它工作)也会比正则表达式匹配更好吗?

$arr = 'Ha.pp.yB.ir.th.da.y';
$strip = '';
for ($i = 1; $i < strlen($arr); $i += 2) {
$arr[$i] = $strip; 
}

【问题讨论】:

    标签: php strlen


    【解决方案1】:

    一种方法是:

    <?php
    $oldString = 'Ha.pp.yB.ir.th.da.y';
    $newString = "";
    
    for ($i = 0; $i < strlen($oldString ); $i++) // loop the length of the string
    {
      if (($i+1) % 3 != 0) // skip every third letter
      {
        $newString .= $oldString[$i];  // build up the new string
      }
    }
    // $newString is HappyBirthday
    echo $newString;
    ?>
    

    或者,如果您要删除的字母始终是同一个字母,则 explode() 函数可能会起作用。

    【讨论】:

    • 感谢您的帮助,尤其是评论,但我得到的输出是 a.p.B.r.h.a. ?
    • 看起来我的测试有点不对劲,我现在已经修好了,你可以在ideone.com/da4dS看到
    【解决方案2】:

    这可能有效:

    echo preg_replace('/(..)./', '$1', 'Ha.pp.yB.ir.th.da.y');
    

    使其具有通用性:

    echo preg_replace('/(.{2})./', '$1', $str);
    

    2 在这种情况下意味着您保留两个字符,然后丢弃下一个。

    【讨论】:

    • preg_replace('/([A-Za-z]{2})./', '$1', $str);会更安全
    【解决方案3】:

    一种方法:

    $old = 'Ha.pp.yB.ir.th.da.y';
    $arr = str_split($old); #break string into an array
    
    #iterate over the array, but only do it over the characters which are a
    #multiple of three (remember that arrays start with 0)
    for ($i = 2; $i < count($arr); $i+=2) {
        #remove current array item
        array_splice($arr, $i, 1);
    }
    $new = implode($arr); #join it back
    

    或者,使用正则表达式:

    $old = 'Ha.pp.yB.ir.th.da.y';
    $new = preg_replace('/(..)\./', '$1', $old);
    #selects any two characters followed by a dot character
    #alternatively, if you know that the two characters are letters,
    #change the regular expression to:
    /(\w{2})\./
    

    【讨论】:

      【解决方案4】:

      我只使用array_map 和一个回调函数。大概是这样的:

      function remove_third_char( $text ) {
          return substr( $text, 0, 2 );
      }
      
      $text = 'Ha.pp.yB.ir.th.da.y';
      $new_text = str_split( $text, 3 );
      
      $new_text = array_map( "remove_third_char", $new_text );
      
      // do whatever you want with new array
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-02
        • 1970-01-01
        • 1970-01-01
        • 2017-02-21
        相关资源
        最近更新 更多