Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ctype_alpha but allow spaces(php)

Tags:

php

I was wondering if one can allow spaces in a textfield when checking it with ctype_alpha. Since ctype_alpha only allows alphabetical letters, I don't know how to let the user enter space in the field. I did try using ctype_space but that didn't work. I simply want the user to be able to type only alphabets and they have a choice to include spaces if they "wish." I hope I will not have to use regexp.

elseif (!ctype_alpha($fname))
{
    echo "Your name may only contain alphabetical letters";   
}
like image 483
Raj Avatar asked May 29 '10 22:05

Raj


2 Answers

this is what I would do

if (!ctype_alpha(str_replace(' ', '', $fname)))

this allows for spaces only, but if you want to allow more than just spaces, like punctuation or what not, read up on str_replace, it allows for arrays

str_replace(array(' ', "'", '-'), '', $fname)

I'm suggesting this because First Name may have apostrophe and last name may also have dashes

like image 148
hndcrftd Avatar answered Oct 23 '22 08:10

hndcrftd


You can do that also by simply removing space before you do ctype_alpha.

$fname=str_replace(" ", "", $fname);

if(!ctype_alpha($fname)){
  echo "Your name may only contain alphabetical letters";
}
like image 29
Freeman Avatar answered Oct 23 '22 06:10

Freeman