简体   繁体   中英

Having trouble searching a string

Okay I have a csv file that gets parsed and displayed. I want to make it searchable. So I have a form that accepts a user query and compares it to the array to find matches. Now here's what I have:

foreach( $last as $key=>$string ) {
   $hits[$key] = strpos( strtolower( $string . " " . $first[$key] . " " . $middle[$key] ), $query );
}

Before this little snippet I force $query to lower also.

So basically this concatenates the full name, Last First Middle, and searches each array item for a match. Then if $hits[$key] != false I can say that there was a match there. So I go back and display that result from the main array of names. Hopefully that makes sense...

Now on the plus side, I will get many results that should show up. Like if I search jo , a list will come up with all of the Johnson last names.

The issue I'm having is results turning up that don't match the query or results not showing up when I know they are in the list of names. So I'll know smith john should return a result, but it will come back with no results.

This is the first time I've really worked on something with a search functionality so I want to do it right.

The strpos() function returns the index of matched substring, meaning it could possibly return 0 :

strpos('foo', 'f'); // 0

If the substring is not found, it will return FALSE .

strpos('foo', 'z'); // FALSE

Because both 0 and FALSE are falsy values (meaning they both evaluate to boolean FALSE ), you will need to use strict checking:

foreach( $last as $key=>$string ) {
   $hits[$key] = strpos( strtolower( $string . " " . $first[$key] . " " . $middle[$key] ), $query ) !== FALSE;
}

Notice the strpos(...) !== FALSE instead of just strpos(...) .

Edit (for @baudday):

Code:

<?php
$query = strtolower('Michael');

$last = array('Baier', 'Baker', 'Baker', 'Banfield', 'Banks', 'Barber');
$first = array('Michael', 'Michael', 'Stephanie', 'Christopher', 'Joseph', 'David');
$middle = array('Joseph', 'Daniel', 'Nicole', 'Phillip', 'Andrew', 'Daniel');

foreach ( $last as $key=>$string ) {
    $haystack = $string . " " . $first[$key] . " " . $middle[$key] . " " . $first[$key] . " " . $middle[$key] . " " . $last[$key] . " " . $first[$key] . " " . $string . " " . $middle[$key];
    $hits[$key] = strpos( strtolower( $haystack ), $query ) !== false;
}

foreach ($hits as $key => $matches) {
    if ($matches) {
        echo $last[$key] . ', ' . $first[$key] . ' ' . $middle[$key] . ' (key: ' . $key . ") matches the query.\n";
    }
}

Output:

Baier, Michael Joseph (key: 0) matches the query.
Baker, Michael Daniel (key: 1) matches the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM