Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove elements from an array that do not match a regex

Tags:

arrays

regex

php

In PHP, is there a function or anything else that will remove all elements in an array that do not match a regex.

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

My array's come in like this, from a form (they're tags actually)

Original array from form. Note: evil tags

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

Cleaned array. Note, no evil tags

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

I currently do like this, but is there a better way? Without the loop maybe?

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

print_r($arr);
like image 758
Norman Avatar asked Sep 09 '14 05:09

Norman


2 Answers

You could use preg_grep() to filter the array entries that match the regular expression.

$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
)
like image 103
hwnd Avatar answered Sep 19 '22 19:09

hwnd


I would not necessarily say it's any better per se, but using regexp and array_filter could look something like this:

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

Where we're returning the result of the preg_match which is either true/false. In this case, it should correctly remove the matched evil tags.

Here's your eval.in

like image 40
Ohgodwhy Avatar answered Sep 18 '22 19:09

Ohgodwhy