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

后端 未结 4 1936
礼貌的吻别
礼貌的吻别 2020-12-21 12:02

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
$A         


        
相关标签:
4条回答
  • 2020-12-21 12:19

    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.

    0 讨论(0)
  • 2020-12-21 12:25

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-21 12:39

    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.

    0 讨论(0)
  • 2020-12-21 12:41

    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;
        }
    }
    
    0 讨论(0)
提交回复
热议问题