2

How do I glob for entries of an array, like glob() does on the filesystem in PHP?

an example:

var_dump(glob_array('pattern*', array('p', 'pattern', 'pattern_123', 'wurstbrot'));
array(2) {
  [0]=>
  string(7) "pattern"
  [1]=>
  string(11) "pattern_123"
}
5
  • 1
    php.net/manual/en/function.array-filter.php ? Commented Aug 28, 2014 at 16:05
  • @PeeHaa Thanks, but that does not implement the globbing. Commented Aug 28, 2014 at 16:14
  • 3
    Why do you guys think this is offtopic? Could you elaborate? I'm baffled! Commented Aug 28, 2014 at 18:23
  • To the guys who closed this question as off-topic (@Marcin-Orlowski VMai jaypal Rebse Jean): It is not - this is a question about a functionality inside of the php standard library. Now I know that it is called fnmatch() - check out the answer I accepted. Commented Aug 28, 2014 at 20:36
  • 2
    Yea, I can't see why this was closed to begin with. Commented Aug 28, 2014 at 21:04

1 Answer 1

3

Check out the fnmatch() function

function glob_array($pattern, array $array, $flags = 0)
{
    return array_filter($array, function($val) use($pattern, $flags){
        return fnmatch($pattern, $val, $flags);
    });
}


print_r(glob_array('pattern*', array('p', 'pattern', 'pattern_123', 'wurstbrot')));

Output:

Array
(
    [1] => pattern
    [2] => pattern_123
)
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer, but this is not quite what I am searching for. In fact, there a huge differences between globbing and regular expressions: en.wikipedia.org/wiki/Glob_%28programming%29
@tback Oh i got what you mean, try using fnmatch()
Nice, that's what I was searching for!

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.