Searching partial strings PHP

后端 未结 3 1780
我寻月下人不归
我寻月下人不归 2021-02-09 06:25

How can you search a partial string when typing (not to use MySQL) like the LIKE function in MySQL but using PHP when searching a string, e.g.



        
3条回答
  •  抹茶落季
    2021-02-09 06:44

    I tend to use strpos

    $needle='appy';
    $haystack='I\'m feeling flappy, and you?';
    
    if(strpos($haystack,$needle)!==false){
       //then it was found
       }
    

    If you want it to ignore case, use stripos.

    Note that a subtlety about this is that if the needle is at the very start of the haystack, in position 0, integer 0 is returned. This means you must compare to false, using strict comparison, or it can produce a false negative.

    As noted in the manual, linked above

    Warning

    This function may return Boolean FALSE, but may also return a non-Boolean value which evaluates to FALSE, such as 0 or "". Please read the section on Booleans for more information. Use the === operator for testing the return value of this function.

    As far as using arrays, strpos is meant to take two strings. Using an array will produce Warning: strpos() expects parameter 1 to be string, array given or 1Warning: strpos(): needle is not a string or an integer`.

    Okay, let's say you have an array of strings for which to search.

    You can

    $needles=array('hose','fribb','pancake');
    $haystack='Where are those pancakes??';
    
    foreach($needles as $ndl){
       if(strpos($haystack,$ndl)!==false){ echo "'$ndl': found
    \n"; } else{ echo "'$ndl' : not found
    \n"; } }

    Another way of searching for multiple strings in one string, without using an array... This only tells you whether at least one match was found.

    $haystack='Where are those pancakes??';
    $match=preg_match('#(hose|fribb|pancake)#',$haystack);
    //$match is now int(1)
    

    Or, use preg_match_all to see how many matches there are, total.

    $all_matches=preg_match_all('#(hose|fribb|pancake)#',$haystack,$results);
    //all_matches is int(2). Note you also have $results, which stores which needles matched.
    

    In that, the search term is a regular expression. () groups the terms together, and | means 'or'. # denotes the beginning and end of the pattern. Regexes can get pretty complicated quickly, but of course, they work! They are often avoided for performance reasons, but if you're testing multiple strings, this might be more efficient than they array looping method described above. I'm sure there are also other ways to do this.

提交回复
热议问题