Reputation: 102
I have here a function for stripos with multiple needle.
function strposa($haystack, $needles=array()) {
$chr = array();
foreach($needles as $needle) {
$res = stripos($haystack, $needle);
if ($res !== false) $chr[$needle] = $res;
}
if(empty($chr)) return false;
return min($chr);
}
$needles = array('Apple', 'Orange', 'Mango');
$haystack = "I love apple";
if(strposa($haystack,$needle)) {
echo "found a match!";
//print apple here
}
else {
echo "no match found.";
}
The function is working fine. What I want is to print the result of the match from haystack. in this case I want to print the word "apple". how should i do that?
Upvotes: 1
Views: 171
Reputation: 2525
You can give a try to this :
function strposa($haystack, $needles=array()) {
$chr = array();
foreach($needles as $needle) {
$res = stripos($haystack, $needle);
if ($res !== false)
{
$chr[$needle] = $res;
$string_exist = $needle; break;
}
}
if(empty($chr)) return false;
return $string_exist;
}
$needles = array('Apple', 'Orange', 'Mango');
$haystack = "I love apple";
$match_found = strposa($haystack,$needles);
if($match_found) {
echo $match_found ;
//print apple here
}
else {
echo "no match found.";
}
There is another way too to achieve the same result :
$needles = array('Apple', 'Orange', 'Mango');
$haystack = "I love apple";
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,strtolower($a)) !== false) return $a;
}
return 0;
}
echo contains($haystack, $needles);
Upvotes: 1
Reputation: 6081
try this:
function strposa($haystack, $needles=array()) {
$chr = array();
foreach($needles as $needle) {
$res = stripos($haystack, $needle);
if ($res !== false) $chr= $needle;
}
if(empty($chr)) return false;
return $chr;
}
if(strposa($haystack,$needle)) {
$ans = strposa($haystack,$needle);
echo $ans;
//print apple here
}
else {
echo "no match found.";
}
Upvotes: 1