2017-07-14 50 views
-2

的所有元素如何一个阵列中的每个元素上应用的preg_match应用的preg_match数组

$array = [abc,def,ghi]; 

现在我做这个

foreach($array as $one_element){ 
    if(!preg_match("/^[a-zA-Z0-9_. -]{1,23}$/",$one_element)){ 
     die("One of element name is not valid"); 
    } 
} 

有没有什么更容易和更快的方式做这个 ?

回答

-1

是的,array_map

array_map(
    function($elem) { 
     if (!preg_match('/^[a-zA-Z0-9_. -]{1,23}$/', $elem)){ 
      die("One of element name is not valid"); 
     } 
    }, 
    $array 
); 
+0

谢谢!看起来不错 – beginner

+0

8行代替5.太棒了! –

+0

@u_mulder一行:'array_map( function($ elem){ if if(!preg_match('/^[a-zA-Z0-9_。 - ] {1,23} $ /',$ value)){ die(“其中一个元素名称无效”); } }, $ array );':-) – Andreas