1

我有一个名为“items”的父级的 PHP 数组。在该数组中,我想删除所有不包含字符串的值(我将使用正则表达式来查找)。我该怎么做?

4

2 回答 2

5
foreach($array['items'] as $key=>$value) { // loop through the array
    if( !preg_match("/your_regex/", $value) ) {
        unset($array['items'][$key]);
    }
}
于 2012-04-26T17:19:46.230 回答
2

您可以尝试使用array_filter.

$items = array(
    #some values
);
$regex= '/^[some]+(regex)*$/i';
$items = array_filter($items, function($a) use ($regex){
    return preg_match($regex, $a) !== 0;
});

注意:这只适用于 PHP 5.3+。在 5.2 中,您可以这样做:

function checkStr($a){
    $regex= '/^[some]+(regex)*$/i';
    return preg_match($regex, $a) !== 0;
}

$items = array(
    #some values
);
$items = array_filter($items, 'checkStr');
于 2012-04-26T17:16:55.467 回答