duanfan8360 2017-06-05 21:54
浏览 147
已采纳

如何在数组中查找包含给定子字符串的元素?

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条回答 默认 最新

  • dppb79372 2017-06-05 21:59
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了
手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部