循环遍历数组并应用preg_match


loop through an array and apply preg_match

我需要遍历一个多维数组,如果不是以字母开头,则只检查标题,如下所示:

Array
(
    [0] => Array
        (
            [letter] =>  
            [id] => 176
        )
    [1] => Array
        (
            [letter] => "
            [id] => 175
        )
.....etc  

所以我只需要检查字母,如果不是以a-zA-z开头,我已经尝试过了,但仍然缺少一些东西,

$notMatch = array();
foreach ($data as $value) {
    foreach ($value as $item['title']=>$d) {
       if(!preg_match('/^[a-zA-Z]$/',$d)){
           $notMatch[]=$d;
       }
    }
}

请参阅下面的URL,我认为它对您非常有帮助。

更新:

在多维数组上使用preg_match返回键值数组

试试

<?php
$data = array(
    "abc"=>array(
            "label" => "abc",
            "value" => "def",
            "type" => "ghi",
            "desc" => "jkl",
            ),
    "def"=>array(
            "label" => "mno",
            "value" => "qrs",
            "type" => "tuv",
            "desc" => "wxyz",
            ),
    );
$matches = array();
$pattern = "/a/i";  //contains an 'a'
//loop through the data
foreach($data as $key=>$value){
    //loop through each key under data sub array
    foreach($value as $key2=>$value2){
        //check for match.
        if(preg_match($pattern, $value2)){
            //add to matches array.
            $matches[$key]=$value;
            //match found, so break from foreach
            break;
        }
    }
}
echo '<pre>'.print_r($matches, true).'</pre>';
?>

我删除了一个foreach循环,并更改了preg_match模式,删除了字符串/线的开始和字符串/线锚的结束。

我就是这样做的:

// I'm assuming your data array looks something like this:
$data = array(array('title'=>'fjsdoijsdiojsd', 'id'=>3),
                    array('title'=>'oijijsd', 'id'=>5),
                    array('title'=>'09234032', 'id'=>3));
$notMatch = array();
foreach ($data as $value) {
   if(!preg_match('/([a-zA-Z]).*/',$value['title'])){
       $notMatch[]=$value['title'];
       echo 'notmatch! ' . $value['title'];
   }
}

然而,有可能拥有更多regex经验的人可以为您提供更好的模式。:)

http://codepad.viper-7.com/dvUQoW