本文介紹了如何在數組中查找包含給定子字符串的元素?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
限時送ChatGPT賬號..
我有 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() 函數 也是為了這個目的
foreach($Array as $name)
{
if ( strpos($name,$Var1)!==false)
{
echo $name;
echo PHP_EOL;
}
}
輸出:-https://eval.in/812371
注意:- 在 Both 函數中,第一個參數是您要在其中搜索子字符串的字符串.第二個參數是子字符串本身.
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.
這篇關于如何在數組中查找包含給定子字符串的元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!