-3

Is there PHP function (or oneliner) for finding one of strings (stored in array) in other string?

# find one of those strings
$needles = [
'aaa',
'bbb',
];

# anywhere in this string
$haystack = 'ccccccaaa';

# returns TRUE when $haystack contains any of strings in $needles
is_there($needles , $haystack) === true
Martin
  • 1,312
  • 1
  • 15
  • 18
  • 3
    It took less than 10 second and I got -1 without explanation? – Martin Jun 13 '14 at 13:19
  • Possible Duplicate: http://stackoverflow.com/questions/9890919/in-php-is-there-a-function-like-stristr-but-for-arrays – Jeremy Harris Jun 13 '14 at 13:22
  • possible duplicate of [Using an array as needles in strpos](http://stackoverflow.com/questions/6284553/using-an-array-as-needles-in-strpos) – Steve Jun 13 '14 at 13:23
  • @Martin: I didn't downvote, but this is my guess: 1. Your question appears to be poorly researched. 2. You haven't demonstrated any efforts of doing this yourself or show any code that you've tried. 3. Some people didn't understand what is being asked. – Amal Murali Jun 13 '14 at 13:28
  • It's crazy. I am almost afraid to ask questions... What good is it for? I obviously know exactly what I need, so one could think I spent some time thinking about it... – Martin Jun 13 '14 at 13:31
  • @Martin: Don't be afraid. If you have a few minutes of time, please take a read of [this Help Center article](http://stackoverflow.com/help/how-to-ask). It may seem pretty basic, but it's really helpful. I know you're probably frustrated seeing your question get downvoted, but don't take it personally. – Amal Murali Jun 13 '14 at 13:37

1 Answers1

1

Use preg_match():

function is_there($needles, $haystack) {
    $p = sprintf('/%s/', implode('|', $needles));
    return (bool) preg_match($p, $haystack);
}

Usage:

var_dump(is_there($needles , 'ccccccaaa'));
var_dump(is_there($needles , 'foobar'));

Output:

bool(true) 
bool(false)
Amal Murali
  • 75,622
  • 18
  • 128
  • 150