php - Exploding string to array, then searching array for multiple results -
background
users on website can give profile 'keywords', each separated ', '. example:
green apples, bananas, red apples, pears
this stored in database string.
i have livesearch page users can search users keyword. on search, page suggests keywords user types. example, user may type:
apples
and page suggest
green apples
, red apples
.
method
when input sent keywordsearch.php
, page searches following:
$search_string_w = '%'.$search_string.'%'; $stmt = $dbh->prepare('select `keywords` `users` `keywords` ?'); $stmt->execute(array($search_string_w)); while($results = $stmt->fetch(pdo::fetch_assoc)) { $result_array[] = $results; }
this gets row of user has keyword. however, want display each individual keyword search suggestions, if keyword appears multiple times.
if (isset($result_array)) { foreach ($result_array $result) { $keyw = explode(', ', $result['keywords']); $keyk = array_search($search_string, $keyw);
now, $keyw[$keyk]
return single keyword. if search apples
, return green apples
, not red apples
too.
question
how can alter code returns occurrences of searched term?
array_search()
, array_keys()
find apple
given apple
. preg_grep()
give of entries containing apple
such green apple
.
the $result_array
can searched follows preg_grep()
:
$keyw = explode(', ', $result['keywords']); //an array can implode or loop through $keyk = preg_grep("/$search_string/", $keyw); // case-insensitive use: "/$search_string/i"
ideally should have keywords table each keyword own row related user id.
Comments
Post a Comment