In PHP
regex
, I try to come up with a solution in finding strings upon different cases. I have a string which contains words,
$animals = "Elephant Horse Cow";
Now I want to make some cases using preg_match()
and not strpos()
for some reason. I had an array with different strings in it and I want to iterate my array to find the cases. My searching is case-insensitive.
Here are my cases.
1) All animals names present in a string with different order, like
$my_case1 = "Horse Elephant Cow";
2) Any animal would be present in a string but not case 1 , like
$my_case2 = "Horse Elephant";
3) Any animal would be present with plural or an extra string after that, like
$my_case3 = "Horses";
And my array of animals is like,
$all_animals = ["Horses Cows", "Elephant", "Goats", "Goat"];
I made the cases using strpos()
but they are un reliable.
EDIT1: MY CODE
function mySearch($name,$animals)
{
$my_case1 = array();
$my_case2 = array();
$my_case3 = array();
$all_cases = [];
$a = explode(' ', $name);
foreach($a as $key) {
foreach($animals as $animal) {
if ($animal !== $key)
{
if ((strpos( strtolower($key), str_replace(' ', '', strtolower($animal)) ) !== FALSE) && (strpos( strtolower($key), str_replace(' ', '', strtolower($animal)))) == 0)
{
echo $animal. "<br>";
}
else if ((strpos( $key, substr( $animal, 0, -1) ) !== FALSE) && (strpos( $key, $animal ) !== 0) )
{
echo $animal. "<br>";
}
}
if (strpos(strtolower($animal), strtolower($key)) !== false) {
if (strpos($animal, $key) !== false) {
if ($animal !== $key)
{
echo $animal. "<br>";
}
} else
{
echo $animal. "<br>";
}
}
}
}
}
return $all_cases; // empty as testing is directing my echo
}