I have the following string from a form...
Opera \"adds cross-platform hardware\" \"kicks butt\" -hippies
In general I\'ve simpl
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
)
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);
}
?>
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
)
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);