views:

30

answers:

2

Currently I am using ctype_alnum to check for alphanumeric type in csv file. But one of my data has white spaces between them and so ctype_alnum gives me false.

Example: ctype_alnum("Here is 23"); 

So my question is how can I check for white spaces in string in php ?

+1  A: 

You can use:

// returns true if $str has a whitespace(space, tab, newline..) anywhere in it.
function has_whitespace($str) {
  return preg_match('/\s/',$str);
}

Or you can write you own function to check if a string contains only alphabets,digits,spaces:

// returns true if $str has nothing but alphabets,digits and spaces.
function is_alnumspace($str){
  return preg_match('/^[a-z0-9 ]+$/i',$str);
}
codaddict
Rachel
I am using in above pattern, so how can I do in a proper way ?
Rachel
@Rachel: I have updated my answer with a new function is_alnumspace(). If you were using ctype_alnum() before and want to allow spaces as well you can use that function.
codaddict
@codaddict: I do not want to write new function, right now am using builtin function of php and so do we another similar kind of function to check white spaces
Rachel
@Rachel: I'm not aware of any existing library function that check for spaces.
codaddict
+1  A: 

So you want to check if a string consists of a letter (a-z) ignoring case (A-Z) or horizontal white space (space(0x20) and tab(0x09))? That would be:

if (preg_match('/^[a-z\h]+$/i', $string)) {
soulmerge