0

Does the PHP function in_array accept a REGEXP array as second argument ? I couldn't find any relevant information on PHP.net

This is the code I'm currently using :

$haystack = [
    "/^foo$/",
    "/^bar$/",
    "/^foobar$/"
];

function in_reg_array($needle, $haystack) {
    foreach ($haystack as $straw)
        if (preg_match($straw, $needle))
            return TRUE;
    return FALSE;
}

If anyone has a better solution, I'm open to suggestions.

Edit :

I can't use a single regexp with foo|bar|foobar because the haystack varies.

4
  • preg_grep('/^(foo|bar|foobar)$/", ? Commented Dec 6, 2018 at 16:18
  • I know this, but this is a sample, the one I use has variable amount of regexes. Commented Dec 6, 2018 at 16:19
  • 3
    preg_grep("/^(".implode('|',$haystack).")$/" ? Commented Dec 6, 2018 at 16:25
  • 2
    In @FelippeDuarte suggestion, remember that $haystack should not contain /^ and $/, so $haystack = ['foo', 'bar', 'foobar'] Commented Dec 6, 2018 at 16:28

2 Answers 2

1

preg_filter() takes an array of patterns, replaces them, and returns the replaced string. So, if it returns nothing, then you know there were no matches.

function in_reg_array($needle, $haystack) {
    return preg_filter($haystack, '', $needle) !== null;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Why didn't I think of preg_filter earlier ? ^^
1

Another option:

$haystack = [
    "^foo$",
    "^bar$",
    "^foobar$"
];

$string = ['foo', 'bar','baz', 'foo2'];

$result = preg_grep("/(".implode('|',$haystack).")/", $string);

Output:

array(2) {
  [0]=> string(3) "foo"
  [1]=> string(3) "bar"
}

Comments

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.