php_begins Posted February 26, 2012 Share Posted February 26, 2012 <label for="first_name">* First Name </label> <input type="text" name="first_name" maxlength="64" value=<?php echo formatPhone(clean_input($_POST['first_name']); ?>> I have a form where I want to enter a first name. I want the fields to take only alphabets(no numbers). Also when a user enters something like John Doe separated by multiple white spaces, I want it to separate the two words only by a single space. I am not sure how this is done in php. Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted February 26, 2012 Share Posted February 26, 2012 If you only want alpha characters, trim the value, and validate it with ctype_alpha. Quote Link to comment Share on other sites More sharing options...
php_begins Posted February 26, 2012 Author Share Posted February 26, 2012 Thanks..but i do not want to trim all the spaces. If there are multiple white spaces between 2 words, I want to reduce them to one space.. Quote Link to comment Share on other sites More sharing options...
Drongo_III Posted February 26, 2012 Share Posted February 26, 2012 Hey mate This is a bit rough and ready but it will give you the general idea. You need regular expressions for this and i've explained how you test them below: <?php $subject = "abcdc ef"; $pattern = '/^[a-zA-Z\s]+$/'; // This tests the above pattern against the string provided - that would be the string from your form $test = preg_match($pattern, $subject); if($test == true){ echo "all ok"; } else { echo "bad string - please retry"; } // pre_replace will search your string for excess white space and remove it - but it will preserve single spaces $str = preg_replace('/\s\s+/', ' ', $subject); echo $str; Quote Link to comment Share on other sites More sharing options...
Pikachu2000 Posted February 26, 2012 Share Posted February 26, 2012 $value = 'this string has many spaces in it'; $value = trim($value); $value = preg_replace('~\s{2,}~', ' ', $value); if( ctype_alpha(str_replace(' ', '', $value)) ) { // valid value containing only letters and spaces. } else { // validation failed } Quote Link to comment Share on other sites More sharing options...
php_begins Posted February 27, 2012 Author Share Posted February 27, 2012 Thanks a lot! Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.