Reputation: 1430
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?
Upvotes: 1
Views: 299
Reputation: 227270
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');
Upvotes: 2
Reputation: 7253
foreach($array['items'] as $key=>$value) { // loop through the array
if( !preg_match("/your_regex/", $value) ) {
unset($array['items'][$key]);
}
}
Upvotes: 4