How to find elements in array that contain a given

2020-02-15 02:22发布

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.

4条回答
在下西门庆
2楼-- · 2020-02-15 02:42

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.

查看更多
▲ chillily
3楼-- · 2020-02-15 02:45

If you want to "filter" your "array", I recommend using the php function called array_filter() like this:

Code:

$Var1 = "Sant";
$Array=["Hello Santa Claus","Easter Bunny","Santa Claus"];

var_export(array_filter($Array,function($v)use($Var1){return strpos($v,$Var1)!==false;}));

Output:

array (
  0 => 'Hello Santa Claus',
  2 => 'Santa Claus',
)

array_filter() needs the array as the first parameter, and the search term inside of use(). The return portion tells the function to retain the element if true and remove the element if false.

The benefit to this function over a foreach loop is that no output variables needs to be declared (unless you want one). It performs the same iterative action.

查看更多
爱情/是我丢掉的垃圾
4楼-- · 2020-02-15 02:49

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;
    }
}
查看更多
We Are One
5楼-- · 2020-02-15 02:53

You should do it like this. You can use stristr but you have to flip arguments because you are passing wrong arguments. First argument should be haystack and second should be needle.

Try this code snippet here

ini_set('display_errors', 1);

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


foreach ($Array as $name)
{
    if (stristr($name,$Var1)!==false)
    {
        echo $name;
        echo PHP_EOL;
    }
}
查看更多
登录 后发表回答