views:

54

answers:

2

I am in the midst of creating a search service for my PHP website and I was wondering how others have gone about intelligently parsing search terms based on quotation marks (and possibly other symbols in the future).

In others words, the search term screwdriver hammer might yield an array of ['screwdriver', 'hammer'], but "flathead screedriver" hammer might yield ['flathead screwdriver', 'hammer'].

I know I can accomplish this in a sloppy loop, but I'm sure PHP has something built in to handle this.

A: 

Try using preg_split

Something like:

/* $search_term:
*  "flathead screwdriver" hammer -nails
*/

$terms = preg_split("/[\s]*\\\"([^\\\"]+)\\\"[\s]*|[\s]+/", $search_term);

/* $terms = array(
*      0    =>    "flathead screwdriver"
*      1    =>    "hammer"
*      2    =>    "-nails"
*/

$exclude = array();

foreach($terms as $term){
    if(strpos($term, '-') == 0)
        array_push($exclude, substr($term, 1));
}

/* $exclude = array(
*      0    =>    "nails"
*/

Only thing I didn't include is removing "nails" from the $terms array. I'll leave this as an exercise for the reader =)

steven_desu
A: 

I ended up using strtok as per this Previous Post

Dutchie432