Jump to content

trim too many whitespaces and allow only alphabets


php_begins

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.

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;


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

Archived

This topic is now archived and is closed to further replies.

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