开发者

PHP Array - how to save a few lines for matching a long list of characters

I got a question when I was doing some Array in PHP. I don't know how to write the code for the following case:

$arrs = array("a@c", "cr", "exd", "hello", "gg%j", "hwa", "@", "8");

foreach ($arrs as $arr){
// if $ar开发者_Go百科r does not belong to any characters from a to z, 
// then there must be some special character in it.
// Say for example, "a@c" will still be regarded as fine string, 
// since it contains normal characters a and c.
// another example, "gg%j" will also be fine, since it contains g and j.
}


You could use a regex, and the preg_match function :

$arrs = array("abc", "cr", "exd", "hello", "gj", "hwa", "@", "8");
foreach ($arrs as $arr){
    // if $arr does not belong to any characters from a to z, 
    // then there must be some special character in it.
    if (!preg_match('/^[a-z]*$/', $arr)) {
        var_dump($arr);
    }
}

Which would get you the following output :

string '@' (length=1)
string '8' (length=1)


Here, the regex is matching :

  • beginning of string : ^
  • any number of characters between a and z : [a-z]*
  • end of string : $

So, if the string contains anything that's not between a and z, it will not match ; and var_dump the string.


if(!preg_match("/^[a-z]*$/", $arr)) {
    // $arr has something other than just a to z in it
}


$arrs = array("abc", "cr", "exd", "hello", "gj", "hwa", "@", "8");

foreach ($arrs as $arr){
// if $arr does not belong to any characters from a to z, 
// then there must be some special character in it.
   if(preg_match("/[a-zA-Z]+/",$arr)==0)
   {
       echo "There must be a special character in it.";
   }
}

This sounds suspiciously like a homework question...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜