2

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?

4 Answers 4

2

No, PHP does not have the function you need.
EDIT
Create your custom function if you want to use some code more than once.

Sign up to request clarification or add additional context in comments.

2 Comments

better write this in your code directly what if he wants to use it more than once? DRY dies right there. Writing you own function may confuse someone So...never create a new function in PHP in case it confuses someone?
I still can't agree with that. create your custom function only if you are sure you will need to do this action really often should quite simply be create your custom function if you want to use it more than once.
1

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;
}

Fiddle

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.

Comments

0
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));

Comments

-1
$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.

2 Comments

@Bogdan In fact, it is. It implies "you can then simply search the resulting string" - only problem is that you have to choose a delimiter that is not part of any individual array value. That's what makes this approach unsuitable for a generic solution. But it would work for a specific situation, for example if it is clear that the array elements will never contain a comma.
Well, you could also use any other delimiter, like a space. but in fact that solution depends on what you want to do and is not valid for any array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.