Search for a string or part of string in PHP

37,545

Solution 1

array_filter lets you specify a custom function to do the searching. In your case, a simple function that uses strpos() to check if your search string is present:

function my_search($haystack) {
    $needle = 'value to search for';
    return(strpos($haystack, $needle)); // or stripos() if you want case-insensitive searching.
}

$matches = array_filter($your_array, 'my_search');

Alternatively, you could use an anonymous function to help prevent namespace contamination:

$matches = array_filter($your_array, function ($haystack) use ($needle) {
    return(strpos($haystack, $needle));
});

Solution 2

foreach($array as $item){
  if(strpos($item,"mysearchword")!== false){
    echo 'found';
  }
}

or you can use preg_match for more flexible search instead of strpos.

Solution 3

I think Marc B's answer was a good starting point but for me it had some problems. Such as you have to know what the Needle is at "compile time" because you can't dynamically change that value. also if the needle appeared at the start of the string element it would act like it's not there at all. so after a little experimenting I manged to come up with a way around both problems. so you don't have to create a new function for every different needle your going to want to use anymore.

function my_search($haystack)
{
    global $needle;
    if( strpos($haystack, $needle) === false) {return false;} else {return true;}
}

and it would be called like this:

$needle="item to search for";
$matches = array_filter($my_array, 'my_search');

and being as needle is now accessible in the same scope that the rest of the code is you can set needle to any other string variable you wanted, including user input.

Solution 4

Unfortunately, search is one of the more difficult things to do in computer science. If you build for search based on literal string matches or regular expressions (regex), you may find that you'll be unhappy with the relevance of the results that are returned.

If you're interested in rolling up your sleeves and getting a little dirty with a more sophisticated solution, I'd try Zend's Lucene implementation ( http://framework.zend.com/manual/en/zend.search.lucene.html ). I've implemented a search on a site with it. It took a few days, but the results were MUCH better than the 15 minute solution of literal string matching.

PS. Here's an example: http://devzone.zend.com/article/91

Share:
37,545

Related videos on Youtube

Sahir
Author by

Sahir

I make apps!

Updated on July 09, 2022

Comments

  • Sahir
    Sahir almost 2 years

    I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that it only looks for exact match. Do you guys know a better way to do this functionality? Since this is a very small part of what I am actually doing, I was hoping that there was something built in. Any ideas?

    Thanks!

    EDIT: The array contains "products" in this format:

    [6] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 2000-YM
                )
    
            [Name] => Team Swim School T-Shirt
            [size] => YM
            [price] => 15
            [group] => Team Clothing
            [id] => 2000-YM
        )
    
    [7] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 3000-YS
                )
    
            [Name] => Youth Track Jacket
            [size] => YS
            [price] => 55
            [group] => Team Clothing
            [id] => 3000-YS
        )
    

    So I was wondering I can do a search such as "Team" and it would return me first item seen here. I am basing the search on the Name (again this is just something small). I understand that I can find the exact string, I am just stuck on the "best results" if it cannot find the exact item. Efficiency is nice but not required since I only have about 50 items so even if I use a "slow" algorithm it won't take much time.

    • Dave Kiss
      Dave Kiss about 13 years
      You may want to provide the string you are looking for once the regex kings and queens arrive.
  • Mike Branski
    Mike Branski over 11 years
    If your $needle is a single character like in my case, you'll want to make a strict check in case the position index is 0 (vs false if no match is found): return(strpos($haystack, $needle) !== false);
  • B. Clincy
    B. Clincy over 6 years
    I'm trying to figure out where the $haystack variable show up, is that key in the array?
  • Kaleem Nalband
    Kaleem Nalband over 5 years
    I have the same problem, but i have array of search strings. how to check if any of the search string present in the file.
  • mickmackusa
    mickmackusa almost 2 years
    @Marc this is not your finest answer. Please edit to prevent teaching the unstable use of strpos().