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:-
Output:- https://eval.in/812376
You can use php strpos() function also for this purpose
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.
If you want to "filter" your "array", I recommend using the php function called
array_filter()
like this:Code:
Output:
array_filter()
needs the array as the first parameter, and the search term inside ofuse()
. The return portion tells the function to retain the element iftrue
and remove the element iffalse
.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.
you can use
strpos()
function of php to identify if a string consist a substring or not asYou should do it like this. You can use
stristr
but you have to flip arguments because you are passing wrong arguments. First argument should behaystack
and second should beneedle
.Try this code snippet here