Search code examples
phparraysfiltersubstring

How to find elements in array that contain a given substring?


I have 3 strings, I would like to get only the equal strings of them, something like this:

$Var1 = "Sant";
$Array[] = "Hello Santa Claus";   // Name_1
$Array[] = "Santa Claus";         // Name_2

I would like to get both of them because they match "Sant".

With my code I only get Name_2

$len = strlen($Var1);
foreach($Array as $name) 
{
   if (  stristr($Var1, substr($name, 0, $len)))
   {
     echo $name;
   }
}

I understand why I only get Name_2, but I don't know how to solve this situation.


Solution

  • Your code will work too like below:-

    foreach ($Array as $name)
    {
        if (stristr($name,$Var1)!==false)
        {
            echo $name;
            echo PHP_EOL;
        }
    }
    

    Output:- https://eval.in/812376

    You can use php strpos() function also for this purpose

    foreach($Array as $name) 
    {
       if (  strpos($name,$Var1)!==false)
       {
         echo $name;
         echo PHP_EOL;
       }
    }
    

    Output:-https://eval.in/812371

    Note:- In Both function the first argument is the string in which you want to search the sub-string. And second argument is sub-string itself.