Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Background

Users on a website can give their profile 'keywords', each separated with ', '. For example:

green apples, bananas, red apples, pears

This is stored in the database as a string.

I have a livesearch page where users can search for users by keyword. On this search, the page suggests keywords as the user types. For example, a user may type:

apples

and the page will suggest

green apples, red apples.

Method

When the input is sent to keywordsearch.php, the page searches the following:

$search_string_w = '%'.$search_string.'%';
$stmt = $dbh->prepare('SELECT `keywords` FROM `users` WHERE `keywords` LIKE ?');
$stmt->execute(array($search_string_w));
while($results = $stmt->fetch(PDO::FETCH_ASSOC)) {
    $result_array[] = $results;
}

This gets the row of the user who has the keyword. However, all I want to do is display each individual keyword as search suggestions, even if the keyword appears multiple times.

if (isset($result_array)) {
    foreach ($result_array as $result) {
        $keyw = explode(', ', $result['keywords']);
        $keyk = array_search($search_string, $keyw);

Now, $keyw[$keyk] will return a single keyword. So if the search is apples, this will only return green apples and not red apples too.

Question

How can I alter this code so that it returns all occurrences of the searched term?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

array_search() and array_keys() will only find apple given apple. preg_grep() will give any of the entries containing apple such as green apple.

The $result_array can be searched as follows with preg_grep():

$keyw = explode(', ', $result['keywords']);
//an array you can implode or loop through
$keyk = preg_grep("/$search_string/", $keyw);
// for case-insensitive use:  "/$search_string/i"

Ideally you should have a keywords table with each keyword as its own row with related user id.

share|improve this answer
    
Perfect - thanks. This is ideal. And you're right about having keywords in their own table - but the developer I'm working under doesn't seem to agree with me! Thanks again. –  Ben Pearl Kahan Apr 23 at 16:08

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.