Connecting Tech Pros Worldwide Help | Site Map

Split by spaces but not when phrase is inside quotes

Newbie
 
Join Date: Sep 2009
Posts: 1
#1   Sep 30 '09
Handy for creating a search query.

There's a suggested answer on the messageboard, but I think this is cleaner.

Expand|Select|Wrap|Line Numbers
  1. $phrases = explode('"', $q);
  2. foreach ($phrases as $k => $v) {
  3.         if (!$v) continue;
  4.         if ($k % 2) {
  5.             $filters[] = $v;
  6.             continue;
  7.         }
  8.         $a = explode(' ', $v);
  9.         foreach ($a as $word) {
  10.             if (!$word) continue;
  11.             $filters[] = $word;
  12.         }
  13. }
  14. print_r($filters);
  15. exit;
  16.  

Last edited by TRiG; Sep 30 '09 at 02:04 PM. Reason: Changing "PHP" tags to "code" tags



Atli's Avatar
Moderator
 
Join Date: Nov 2006
Location: Iceland
Posts: 3,745
#2   Oct 1 '09

re: Split by spaces but not when phrase is inside quotes


Hey.

You could also try a regular expression:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. $regex = '/"[^"]+"|[^"\s]+/i';
  3. if(preg_match_all($regex, $q, $matches)) {
  4.     print_r($matches[0]);
  5. }
  6. else {
  7.     echo "Empty query";
  8. }
  9. ?>
Should be a bit faster, I'd guess.
Reply