問題描述
我有 3 個字符串,我只想得到它們的相等字符串,如下所示:
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
我想同時獲取它們,因為它們匹配 Sant".
I would like to get both of them because they match "Sant".
使用我的代碼我只能得到 Name_2
With my code I only get Name_2
$len = strlen($Var1);
foreach($Array as $name)
{
if ( stristr($Var1, substr($name, 0, $len)))
{
echo $name;
}
}
我明白為什么我只得到Name_2
,但我不知道如何解決這種情況.
I understand why I only get Name_2
, but I don't know how to solve this situation.
推薦答案
你的代碼也會像下面這樣工作:-
foreach ($Array as $name)
{
if (stristr($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
輸出:- https://eval.in/812376
您可以使用php strpos() 函數(shù) 也是為了這個目的
foreach($Array as $name)
{
if ( strpos($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
輸出:-https://eval.in/812371
注意:- 在 Both 函數(shù)中,第一個參數(shù)是您要在其中搜索子字符串的字符串.第二個參數(shù)是子字符串本身.
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.
這篇關于如何在數(shù)組中查找包含給定子字符串的元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!