【问题标题】:Explode over every other word爆炸超过所有其他单词
【发布时间】:2009-05-08 16:53:50
【问题描述】:

假设我有一个字符串:

$string = "This is my test case for an example."

如果我确实基于''爆炸,我会得到一个

Array('This','is','my','test','case','for','an','example.');

我想要的是其他空间的爆炸:

Array('This is','my test','case for','an example.').

字符串可能包含奇数个单词,因此数组中的最后一项可能不包含两个单词。

有人知道怎么做吗?

【问题讨论】:

    标签: php explode


    【解决方案1】:

    我会查看结果,并在事后连接字符串。

    【讨论】:

    • 哦是的好主意 - 一个递增 2 并连接的 for 循环 - 谢谢。
    • 似乎是最简单的方法。
    【解决方案2】:
    $matches = array();
    preg_match_all('/([A-Za-z0-9\.]+(?: [A-Za-z0-9\.]+)?)/',
           'This is my test case for an example.',$matches);
    
    print_r($matches);
    

    产量:

    Array
    (
      [0] => Array
        (
            [0] => This is
            [1] => my test
            [2] => case for
            [3] => an example.
        )
    
      [1] => Array
        (
            [0] => This is
            [1] => my test
            [2] => case for
            [3] => an example.
        )
    
    )
    

    更新修复它以匹配句子末尾的单个单词

    【讨论】:

    • 很好,如果可能,请在末尾添加检查以查看最后一个元素是否具有问题所要求的单个元素。
    • 去掉括号,你会得到一个数组。
    • 很好地解决了这个问题,但我要为丹尼尔的回答 +1,抱歉。虽然这是正确且有效的,但另一种方法会更易于理解和维护,IMO。
    【解决方案3】:

    可用于不同分隔符和数字的函数。

    function explodeEveryNth($delimiter, $string, $n) {
        $arr = explode($delimiter, $string);
        $arr2 = array_chunk($arr, $n);
        $out = array();
        for ($i = 0, $t = count($arr2); $i < $t; $i++) {
            $out[] = implode($delimiter, $arr2[$i]);
        }
        return $out;
    }
    

    测试代码

    var_dump(explodeEveryNth(' ', 'This is a test string', 2));
    

    【讨论】:

    • 是的,这绝对比我的干净。我喜欢!我实际上只是在探索递归函数,所以我想看看我是否可以那样做。我测试了你的,它的速度更快......对于 1502 个单词:Chunk Explode = 0.49018907546997 seconds vs. Explode Every N = 0.0034539699554443 seconds。
    • 谢谢!为我工作。
    【解决方案4】:

    $string = "This is my test case for an example.";
    
    preg_match_all("/[a-zA-Z0-9]+\ [a-zA-Z0-9]+/", $string, $matches);
    print_r($matches);
    

    【讨论】:

    • 如果任何单词中出现非字母数字字符,这将窒息。
    • 所以修改它:这只是一个例子。
    【解决方案5】:
    $matches = array();
    preg_match_all('/\S+(?:\s[A-Za-z0-9.]+|$)/',
        'This is my test case for an example.',
        $matches
    );
    print_r($matches);
    preg_match_all('/\S+(?:\s[A-Za-z0-9.]+|$)/',
        'This is my test case for example.',
        $matches
    );
    print_r($matches);
    

    【讨论】:

      【解决方案6】:

      您可以在其他场景中重复使用的东西:(总是更好的 IMO)。

      虽然可能不是最优雅的解决方案,但这确实遵循了其他 PHP 核心函数的一般概念语法......

      无论如何...这使用递归。它很灵活,因为它允许您指定块的大小(以防您想在以后或其他项目中这样做)。我这样做更像是一个个人挑战,看看我能想出什么。

      <?php
      function chunk_explode($glue=' ',$pieces='',$size=2,$final=array()) {
          if(!is_string($pieces) && !is_array($pieces)) 
              return false;
      
          if(is_string($pieces))
              $pieces = explode($glue,$pieces);
      
          $num_pieces = sizeof($pieces);
          if($num_pieces <= 0) 
             return $final;
      
          if($num_pieces >= $size) {
              $arr_chunk = array_chunk($pieces, $size);
              array_push($final,implode($glue,$chunk[0]));
              for($i=0;$i<=$size;$i++) { array_shift($pieces); }
              return chunk_explode($glue,$pieces,$size,$final);
          }
          array_push($final,implode($glue,$pieces));
          return $final;
      }
      $string = "This is my test case for an example.";
      chunk_explode(' ',$string,3);
      

      如果这个 chunk_explode 函数很糟糕,请告诉我,以便我从错误中吸取教训。

      【讨论】:

      • 由于您需要通知,我为您可能感兴趣的这个问题提供了不同的解决方案。
      【解决方案7】:

      PHP中有75个数组函数,我们试试用它们代替for循环!!

      我喜欢 Kyle 的函数名。 (我假设您没有运行 5.3 并遭受 create_function 的影响。)

       function chunk_explode($string, $chunks = 2, $delim = ' ') {
           $A = explode($delim, $string);
           $A = array_chunk($A, $chunks);
           return array_map(
               create_function('$x',
                  'return implode(\'' . $delim . '\',$x);'), $A);
       }
      

      【讨论】:

      • array_map 比 for 循环慢。它仅对迭代多个数组有用。 create_function 也很慢,至少做个辅助函数还是等PHP5.3吧。
      • Array_map 比 for 循环更具可读性。我的回答指出 PHP 5.3 避免了 create_function 的痛苦,你为什么要重申我所说的?同样,如何将 $delim 传递给从 array_map 调用的单独函数?
      【解决方案8】:
          $str = "This is my test case for an example.";
          $arr = split(' ', $str);
          $newArr = array();
          $count = count($arr);
          for($i=0;$i<$count;$i = $i + 2) {
              $newArr[] = $arr[$i] . ' ' . $arr[$i+1];
          }
      
      
      array(4) {
        [0]=>
        string(7) "This is"
        [1]=>
        string(7) "my test"
        [2]=>
        string(8) "case for"
        [3]=>
        string(11) "an example."
      }
      

      【讨论】:

        【解决方案9】:

        显然这不是最好的解决方案,但以我自己的方式解决它很有趣。还有很多东西要学...

        function solveThisPuzzle($string) {
        
        $modified_string = preg_replace('(\s)', '+', $string, -1, $count);  
        $words = explode('+', $modified_string);
        
        $phrases_arr = array();
        
        for($i = 1; $i < $count+1; $i++) {
            if(($i % 2)) {
                $phrase = $words[$i-1].' '.$words[$i];
                $phrases_arr[] = $phrase;
                unset($phrases_arr[$i]);
            } elseif($i == $count) {
                    $phrase = $words[$i];
                    $phrases_arr[] = $phrase;
                } else {            
                    $phrase = NULL;
                }
        }
        
        foreach($phrases_arr as $final_phrase) {
            $solution .= $final_phrase.'<br />';
        }
        
            return $solution;
        

        }

        $string = "This is my test case for an example, huzzah!";
        echo solveThisPuzzle($string);
        
        This is
        my test
        case for
        an example,
        huzzah!
        

        【讨论】:

          【解决方案10】:

          我不会在我自己的项目中使用任何以前发布的答案。

          最干净、最直接的工具是preg_split()。匹配第一个非空格字符序列,然后是空格,然后是下一个非空格字符序列,然后“忘记”匹配的字符并匹配爆炸过程中必须消耗的空间。

          \K 表示“从这里重新开始全字符串匹配”。使用\K 消除了实现捕获组以及PREG_ 标志的需要。

          代码:(Demo)

          $string = "This is my test case for an example.";
          
          var_export(
              preg_split('~[^ ]+ [^ ]+\K ~', $string)
          );
          

          输出:

          array (
            0 => 'This is',
            1 => 'my test',
            2 => 'case for',
            3 => 'an example.',
          )
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-12-15
            • 2016-02-23
            • 1970-01-01
            • 2012-04-06
            • 1970-01-01
            • 1970-01-01
            • 2020-05-20
            • 2011-08-18
            相关资源
            最近更新 更多