RE: RegExp for preg_split()

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Thanks,

But this example seems to be short and does the job :

<?php
$String='this is a "test expression" for search input';
$MyRegEx = '/"[^"]+"|[^"\s,]+/';
preg_match_all($MyRegEx, $String, $Tokens);  
?>

Unless I'm missing something?

thanks

-----Original Message-----
From: Richard Lynch [mailto:ceo@xxxxxxxxx] 
Sent: Saturday, April 29, 2006 10:29 AM
To: Weber Sites LTD
Cc: php-general@xxxxxxxxxxxxx
Subject: Re:  RegExp for preg_split()

On Fri, April 28, 2006 11:16 am, Weber Sites LTD wrote:
> I'm looking for the RegExp that will split a search string into search 
> keywords.
> while taking " " into account.
>
> From what I managed to find I can get all of the words into an array 
> but I would like all of the words inside " " to be in the same array 
> cell.

I'd be pretty surprised if searching for things like:
PHP simple search input quotes
and things like that didn't turn up some solutions...

You might have to search in specific forums rather than a general Google,
but.

Here's one crude solution though:

<?php
$input = 'this is a "test expression" for search input'; //remove duplicate
spaces:
$input = preg_replace('/\\s+/', ' ', $input); //ignore leading/trailing
blanks:
$input = trim($input);
$parts = explode('"', $input);
$terms = array();
$in_quotes = false;
foreach($parts as $expression){
  $expression = trim($expression); //probably not needed...
  if (strlen($expression)){
    if (!$in_quotes){
      //individual words:
      $words = explode(' ', $expression);
      $terms = array_merge($terms, $words);
    }
    else{
      //in quotes, so this is a search term:
      $terms[] = $expression;
    }
  }
  $in_quotes = !$in_quotes;
}
var_dump($terms);
?>

Note that invalid input such as unbalanced quote marks will mess this up
big-time, probably...

But maybe that's just as well...

--
Like Music?
http://l-i-e.com/artists.htm

--
PHP General Mailing List (http://www.php.net/) To unsubscribe, visit:
http://www.php.net/unsub.php

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux