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

吃可爱长大的小学妹 提交于 2019-12-01 12:14:49

问题


I have the following string from a form...

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

In general I've simply been using the following...

$p0 = explode(' ',$string);

However now I want to maintain any and all quote operators as a single array item instead of having them create individual items like "adds, cross-platform and hardware".

I want to have that string end up creating an array like this...

Array
(
    [0] => 'Opera',
    [1] => 'adds cross-platform hardware',
    [2] => 'kicks butt',
    [3] => '-hippies'
)

I generally prefer to not use regex for most things whenever possible.


回答1:


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);



回答2:


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
)



回答3:


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);
}
?>



回答4:


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

)



来源:https://stackoverflow.com/questions/12136277/php-explode-terms-in-to-array-retain-quoted-text-as-single-array-item

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!