PHP explode terms in to array, retain quoted text as single array item

前端 未结 4 2000
粉色の甜心
粉色の甜心 2021-01-17 00:11

I have the following string from a form...

Opera \"adds cross-platform hardware\" \"kicks butt\" -hippies

In general I\'ve simpl

相关标签:
4条回答
  • 2021-01-17 00:45

    If you're using PHP >= 5.3, you can use str_getcsv

    print_r(str_getcsv('Opera "adds cross-platform hardware" "kicks butt" -hippies'," "));
    

    prints

    Array
    (
        [0] => Opera
        [1] => adds cross-platform hardware
        [2] => kicks butt
        [3] => -hippies
    )
    
    0 讨论(0)
  • 2021-01-17 00:47

    try this without using regex, a rough code

    <?
    $string='Opera "adds cross-platform hardware" "kicks butt" -hippies';
    $g=explodeMe($string);
    echo "<pre>";
    print_r($g);
    echo "</pre>";
    
    function explodeMe($string){
        $k=explode('"',$string);
        foreach ($k as $key => $link)
        {
            if ($k[$key] == ' ')
            {
                unset($k[$key]);
            }
        }
        return array_values($k);
    }
    ?>
    
    0 讨论(0)
  • 2021-01-17 00:57

    While I'm looking for the fastest approach I thought I would add my own approach to the challange.

    <?php
    $q = 'Opera "adds cross-platform hardware" "kicks butt" -hippies';
    echo '<div>'.$q.'</div>';
    $p0 = explode(' ',$q);
    echo '<div><pre>';print_r($p0);echo '</pre></div>';
    
    $open = false;
    $terms = array();
    foreach ($p0 as $key)
    {
     if ($open==false)
     {
      if (substr($key,0,1)=='"')
      {
       $open = $key;
      }
      else {array_push($terms,$key);}
     }
     else if (substr($key,strlen($key) - 1,strlen($key))=='"')
     {
      $open = $open.' '.$key;
      array_push($terms,$open);
      $open = false;
     }
     else
     {
      $open = $open.' '.$key;
     }
    }
    
    echo '<div><pre>';print_r($terms);echo '</pre></div>';
    
    echo '<div><pre>';print_r($open);echo '</pre></div>';
    ?>
    

    Outputs the following...

    Opera "adds cross-platform hardware" "kicks butt" -hippies

    //Initial explode by spaces...

    Array (

    [0] => Opera
    [1] => "adds
    [2] => cross-platform
    [3] => hardware"
    [4] => "kicks
    [5] => butt"
    [6] => -hippies
    

    )

    //Final results...

    Array (

    [0] => Opera
    [1] => "adds cross-platform hardware"
    [2] => "kicks butt"
    [3] => -hippies
    

    )

    0 讨论(0)
  • 2021-01-17 01:09

    You could use a preg_match_all(...):

    $text = 'Opera "adds cross-platform hardware" "kicks butt" -hippies';
    preg_match_all('/"(?:\\\\.|[^\\\\"])*"|\S+/', $text, $matches);
    print_r($matches);
    
    0 讨论(0)
提交回复
热议问题