Re: Breaking up search terms into an array intelligently
| From: | Robin Vickery | Date: | Sat, 10 Sep 2005 12:39:36 +0000 |
| Subject: | Re: Breaking up search terms into an array intelligently | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-222110@lists.php.net to get a copy of this message | ||
On 9/7/05, Paul Groves <paul.groves@oucs.ox.ac.uk> wrote:
> I want to be able to break up a number of search terms typed into an input
> box into array, simple enough one would think, just use explode, e.g
>
>
> $array = explode(" ", $string);
>
>
> But what if I want to be able to cope with search terms seperated by > 1
> space (a common typing error)? This should work:
>
>
> function enhanced_explode($string) {
> $array = preg_split ("/\s+/", $string);
> return ($array);
> }
>
>
> But what if I want to allow "Google"-type search parameters, so that
> something like the following is split into 3 search terms?:
> firstsearchterm "second search term" thirdsearchterm
> The following code will do the trick, but is slow and doesn't allow for
> multiple spaces as the delimiter, nor the possibility of multiple delimiters
> (e.g. " ", "+", "," etc.)
<?php
$search ='first -second +third "fourth \"fifth\"" -"sixth
seventh"
eighth';
$re = '/[+-]?("(?:[^"\\\\]|\\\\.)*"|[^\s]+)/';
preg_match_all($re, $search, $terms);
print_r($terms);
?>
Array
(
[0] => Array
(
[0] => first
[1] => -second
[2] => +third
[3] => "fourth \"fifth\""
[4] => -"sixth seventh"
[5] => eighth
)
[1] => Array
(
[0] => first
[1] => second
[2] => third
[3] => "fourth \"fifth\""
[4] => "sixth seventh"
[5] => eighth
)
)