如何查找包含给定子字符串的数组中的元素? [英] How to find elements in array that contain a given substring?

查看:283
本文介绍了如何查找包含给定子字符串的数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  $ Var1我有3个字符串,我只想得到它们的平等字符串。 =Sant; 
$ Array [] =你好圣诞老人; // Name_1
$ Array [] =Santa Claus; // Name_2

我想得到两者,因为它们匹配Sant



使用我的代码,我只得到 Name_2

  $ len = strlen($ Var1); 
foreach($ Array作为$ name)
{
if(stristr($ Var1,substr($ name,0,$ len)))
{
echo $名称;


$ / code $ / pre

我明白为什么我只得到 Name_2 ,但我不知道如何解决这种情况。 $ <名称)
{
if(stristr($ name,$ Var1)!== false)
{
echo $ name;
echo PHP_EOL;


code
$ b

输出: https://eval.in/812376



也可以使用 php strpos()函数
$ b $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ Var1)!== false)
{
echo $ name;
echo PHP_EOL;


code
$ b

输出: https://eval.in/812371



注意: - 在两个函数中,第一个参数是您要在其中搜索子字符串的字符串。第二个参数是子字符串本身。


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.

解决方案

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.

这篇关于如何查找包含给定子字符串的数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆