Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 964
Paul Noris Avatar asked Mar 25 '26 19:03

Paul Noris


2 Answers

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.

like image 193
Anant Kumar Singh Avatar answered Mar 30 '26 13:03

Anant Kumar Singh


you can use strpos() function of php to identify if a string consist a substring or not as

$a = 'Sant';
foreach($Array as $name) 
{
    if (strpos($name, $a) !== false) {
        echo $name;
    }
}
like image 22
RAUSHAN KUMAR Avatar answered Mar 30 '26 12:03

RAUSHAN KUMAR