I have a PHP array with a parent called "items." In that array, I want to remove all values that do not contain a string (which I'm gonna use regex to find). How would I do this?
2 Answers
You can try using array_filter.
$items = array(
#some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
return preg_match($regex, $a) !== 0;
});
NOTE: This only works in PHP 5.3+. In 5.2, you can do it this way:
function checkStr($a){
$regex= '/^[some]+(regex)*$/i';
return preg_match($regex, $a) !== 0;
}
$items = array(
#some values
);
$items = array_filter($items, 'checkStr');
1 Comment
Madbreaks
I prefer this approach to brute force looping over the array, good answer.