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);
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
)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With