Remove elements from array that do not match regex

PHP has a function or something else that will remove all elements in the array that don't match the regex.

My regex is like this: preg_match('/^[a-z0-9\-]+$/i', $str)

My array goes like this: from a form (they are actually tags)

The original array from the form. Note: evil tags

$arr = array (
    "french-cuisine",
    "french-fries",
    "snack-food",
    "evil*tag!!",
    "fast-food",
    "more~evil*tags"
);

      

The cleared array. Notice, no evil tags

Array (
    [0] => french-cuisine
    [1] => french-fries
    [2] => snack-food
    [3] => fast-food
)

      

I love it so much now, but is there a better way? Without a cycle, maybe?

foreach($arr as $key => $value) {
    if(!preg_match('/^[a-z0-9\-]+$/i', $value)) {
        unset($arr[$key]);
    }
}

print_r($arr);

      

+3


source to share


2 answers


You can use preg_grep()

to filter array entries matching regex.

$cleaned = preg_grep('/^[a-z0-9-]+$/i', $arr);
print_r($cleaned);

      



Output

Array
(
    [0] => french-cuisine
    [1] => french-fries
    [2] => snack-food
    [4] => fast-food
)

      

+4


source


I wouldn't say it's better, but using regexp and array_filter might look something like this:

$data = array_filter($arr , function ($item){
    return preg_match('/^[a-z0-9\-]+$/i', $item);
});

      



Where we return the result of preg_match, which is either true / false. In this case, he must correctly remove the matching marks of evil.

Here's your eval.in

+4


source







All Articles