Search code examples
phparraysregexfilteringpreg-grep

Retain array elements containing only letters and hyphens


I have the following Array:

Array
(
    [0] => text
    [1] => texture
    [2] => beans
    [3] => 
)

I am wanting to get rid of entries that don't contain a-z or a-z with a dash. In this case, array item 3 (contains just a space).

How would I do this?


Solution

  • Try with:

    $input = array( /* your data */ );
    
    function azFilter($var){
        return preg_match('/^[a-z-]+$/i', $var);
    }
    $output = array_filter($input, 'azFilter');
    

    Also in PHP 5.3 there is possible to simplify it:

    $input = array( /* your data */ );
    
    $output = array_filter($input, function($var){
        return preg_match('/^[a-z-]+$/i', $var);
    });