Reputation: 193
I just wrote this function :
function Array_in_String($Haystack1, $Values1)
{
foreach ($Values1 as $token1)
{
if (strpos($Haystack1, $token1) !== false) return true;
}
}
that basically searches a string $Haystack1
for multiple values in an array $Values1
and returns true if hits a match.
Before that, I searched a lot in PHP for a similar string function. I'm still wondering if PHP has a similar function?
Upvotes: 2
Views: 263
Reputation: 132071
return array_reduce(
$Values1,
function($result, $token1) use ($Haystack1) {
return $result || strpos($Haystack1, $token1) !== false;
},
false
);
or
$matches = array_map(
function($token1) use ($Haystack1) {
return strpos($Haystack1, $token1) !== false;
},
$Values1
);
return (bool) count(array_filter($matches));
Upvotes: 0
Reputation: 70209
I'm not aware of such a function, but your logic can be greatly simplified by using str_replace
.
function array_in_string($haystack, $needles) {
return str_replace($needles, '', $haystack) !== $haystack;
}
Though, if your needle array is really huge, the code posted in your question may have a better performance as it will return true
in the first match while my solution always iterates over all needles.
Upvotes: 1
Reputation: 5512
No, PHP does not have the function you need.
EDIT
Create your custom function if you want to use some code more than once.
Upvotes: 2
Reputation: 5092
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
this produces:
"lastname,email,phone"
Edit: of course you'll have to make a preg_match on this string afterwards.
Upvotes: -1