Jump to content

trim too many whitespaces and allow only alphabets


Recommended Posts

    <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.

Link to comment
Share on other sites

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:



$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;

Link to comment
Share on other sites

$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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.