tags:

views:

29

answers:

3

Hi all,

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 $arr 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.
}

Could you help me please?

+3  A: 

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.

Pascal MARTIN
A: 
$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...

webdestroya
No this is not homework
A: 
if(!preg_match("/^[a-z]*$/", $arr)) {
    // $arr has something other than just a to z in it
}
Amber