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

前端 未结 4 2003
粉色の甜心
粉色の甜心 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:57

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

    '.$q.'
    '; $p0 = explode(' ',$q); echo '
    ';print_r($p0);echo '
    '; $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 '
    ';print_r($terms);echo '
    '; echo '
    ';print_r($open);echo '
    '; ?>

    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
    

    )

提交回复
热议问题