How could I find all whitespaces excluding the ones between quotes?

前端 未结 5 1527
野性不改
野性不改 2020-12-10 06:48

I need to split string by spaces, but phrase in quotes should be preserved unsplitted. Example:

  word1 word2 \"this is a phrase\" word3 word4 \"this is a s         


        
5条回答
  •  [愿得一人]
    2020-12-10 07:15

    Anybody want to benchmark tokenizing vs. regex? My guess is the explode() function is a little too hefty for any speed benefit. Nonetheless, here's another method:

    (edited because I forgot the else case for storing the quoted string)

    $str = 'word1 word2 "this is a phrase" word3 word4 "this is a second phrase" word5';
    
    // initialize storage array
    $arr = array();
    // initialize count
    $count = 0;
    // split on quote
    $tok = strtok($str, '"');
    while ($tok !== false) {
        // even operations not in quotes
        $arr = ($count % 2 == 0) ? 
                                   array_merge($arr, explode(' ', trim($tok))) :
                                   array_merge($arr, array(trim($tok)));
        $tok = strtok('"');
        ++$count;
    }
    
    // output results
    var_dump($arr);
    

提交回复
热议问题