Dutchie432
Dutchie432

Reputation: 29160

Intelligently parse user search terms in PHP

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.

Upvotes: 1

Views: 1791

Answers (2)

Dutchie432
Dutchie432

Reputation: 29160

I ended up using strtok as per this Previous Post

Upvotes: 0

stevendesu
stevendesu

Reputation: 16801

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 =)

Upvotes: 1

Related Questions