I'm validating my contact form using PHP and I've used the following code:
if (ctype_alpha($name) === false) {
$errors[] = 'Name must only contain letters!';
}
This code is works fine, but it over validates and doesn't allow spaces. I've tried ctype_alpha_s and that comes up with a fatal error.
Any help would be greatly appreciated
Regex is overkill and will perform worse for such a simple task, consider using native string functions:
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
This will strip spaces prior to running the alpha check. If tabs and new lines are an issue you could consider using this instead:
str_replace(array("\n", "\t", ' '), '', $name);
ctype_alpha only checks for the letters [A-Za-z]
If you want to use it for your purpose, first u will have to remove the spaces from your string and then apply ctype_alpha.
But I would go for preg_match to check for validation. You can do something like this.
if ( !preg_match ("/^[a-zA-Z\s]+$/",$name)) {
$errors[] = "Name must only contain letters!";
}
One for the UTF-8 world that will match spaces and letters from any language.
if (!preg_match('/^[\p{L} ]+$/u', $name)){
$errors[] = 'Name must contain letters and spaces only!';
}
Explanation:
[] => character class definition
p{L} => matches any kind of letter character from any language
Space after the p{L} => matches spaces
+ => Quantifier — matches between one to unlimited times (greedy)
/u => Unicode modifier. Pattern strings are treated as UTF-16. Also
causes escape sequences to match unicode characters
This will also match names like Björk Guðmundsdóttir as noted in a comment by Anthony Hatzopoulos above.
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
$errors[] = 'Name must contain letters and spaces only';
}
Related
I know there's are other ways to do it, but I'm playing with validating a name field using ctype_alpha but allowing spaces, hyphens, and apostrophes.
Per another post on Stack, I was able to add the spaces no problem, but I'm thinking I have the syntax wrong for replacing multiple characters.
What I've used so far that works for validating that only letters and spaces are allowed:
if (ctype_alpha(str_replace(' ', '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
This removes any spaces before checking that the string is letters only. I was looking to simply add to this to also allow hyphens and apostrophes.
What I've tried for adding hyphens and/or apostrophes (doesn't work):
if (ctype_alpha(str_replace(' ', '', '-', '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
My guess is that adding a second string in the str_replace function is not proper syntax, but being a PHP newb, I'm having a hard time figuring out how to phrase my searches to find the correct syntax.
Also, am I correct in saying that '\w' will cover my apostrophes once I figure out the correct syntax for the str_replace function?
Genuinely appreciate the help guys. You're all invaluable and I try hard not to abuse it.
the proper syntax, as stated in the manual is:
if (ctype_alpha(str_replace(array(' ', '', '-'), '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
With apostrophe
if (ctype_alpha(str_replace(array(' ', '', '-',"'"), '', $name)) === false) {
echo'Name must contain letters and spaces only';
exit;
}
Using '\w' is unfeasible with respect to the apostrophe, i.e. a single quote character. Per the manual:
\w Any word character (letter, number, underscore)
As for the syntax in the OP's code, the primary issue is needing to have an array of characters for the first parameter of str_replace() in order to replace multiple characters.
In addition to enclosing a single quote in double quotes ("'"), PHP permits escaping the single quote character with a backslash and then enclosing it in single quotes, as the following snippet indicates:
<?php
$name = "Kate O'Henry-Smith";
$arrDelChars = [' ','\'','-'];
if ( ctype_alpha( str_replace( $arrDelChars, '', $name ) ) === false ) {
exit( "Name must contain letters and spaces only\n" );
}
print_r($name);
See demo
str_replace() replaces each character in $name with an empty string based on an array of values to exclude. Note, specifying the empty string in the array is needless since the replacement value is the empty string. The new string which emerges becomes the actual parameter for ctype_alpha() instead of $name. Accordingly the function returns true. Consequently, the if-conditional evaluates as false, thereby preventing an error message from displaying. Cute trick for allowing ctype_alpha() to validate $name so-to-speak.
I've got a string called $ID coming in from a different page and hitting base64_decode($enc); and want to check it for any weird characters. $ID when decrypted should only contain letters, numbers, underscores and dashes.
I've had a bit of a look at preg_replace('/[\x80-\xFF]/', '', $string); which cuts out some weird characters---which is helpful---but I can still see sometimes that # signs and brackets and stuff still make it in.
Is there a way I can lower the ascii test? Or how else do I cut out everything except letters, numbers, underscores and dashes?
Any help at pointing me in the right direction is wonderful and thanks!
$enc = $_GET["key"];
$ID= base64_decode($enc);
if (empty($enc)) { echo "key is empty"; } else {
echo "string ok<br>";
$check = preg_replace('/[\x80-\xFF]/', '', $ID);
echo $check;
// i can see this step is helping cut junk out, do more tests from here
}
Typing a caret after the opening square bracket negates the character class, so you can do:
$check = preg_replace('/[^A-Za-z0-9_-]/', '', $ID);
You can use this replacement:
$check = preg_replace('~[^[:word:]-]+~', '', $ID);
The [:word:] character class contains letters, digits and the underscore.
To make the string lowercase, use strtolower()
I have the following code for validating user input for alpha numeric characters
if (!preg_match("/^[A-Za-z][A-Za-z0-9.]*(?:_[A-Za-z0-9]+)*$/", $username)){
echo "invalid username";
}
It checks, whether the input have other characters than (A-Z) (0-9) alpha numeric. Additionally it allows to accept (_) underscore also, but it should be placed in between the strings only as my_name, but it will not accept _myname or myname_.
My question is how can I add a dot(.) character in my above code as same as constrained in underscore as Eg accept (my.name) or (myn.ame) etc but not to accept (.myname) (myname.)
I think this pattern should work for you
$string = 'my_nam.e';
$pattern = '/^[a-z]+([a-z0-9._]*)?[a-z0-9]+$/i';
if ( ! preg_match($pattern, $string))
{
echo 'invalid';
}
I know that there is the function ctype_alpha, though this one will return FALSE when the string contains spaces (white space character).
How do I allow alpha characters and spaces, but nothing else?
$is_alpha_space = ctype_alpha(str_replace(' ', '', $input)));
or
$is_alpha_space = preg_match('/^[a-z\s]*$/i', $input);
if (preg_match("^/[a-zA-Z ]+$/", $input)) {
// input matches
}
Demo: http://ideone.com/jp6Wi
Docs: http://php.net/manual/en/function.preg-match.php
ctype_alpha(preg_replace('/\s/', '', $mystring))
The inner expression returns the string without spaces, and then you use ctype_alpha`` as you wish
Removing the spaces is the way to go, but remember ctype_alpha results in a false on an empty string these days! Below the method I use...
function validateAlpha($valueToValidate, $spaceAllowed = false) {
if ($spaceAllowed) {
$valueToValidate = str_replace(' ', '', $valueToValidate);
}
if (strlen($valueToValidate) == 0) {
return true;
}
return ctype_alpha($valueToValidate);
}
I would work around with a Simple regex and with the php function preg_match() like this:
if(preg_match("/^[a-zA-Z ]+$/", $varToCheck)){
//your code here
}
The important part here is the regex that identifies the parts you want, in my case I wanted text for a name field and with spaces like the case in here.[a-z] is the range from a to z, A-Z are the range from A to Z and the " " at the end represents the spaces.
Hope this helps someone.
How can I alter the pattern below to allow 1 space character ?
$name = 'too long name';
$pattern_name = '/[^a-zA-Z]/';
if (preg_match($pattern_name,$name)) { // remove any non-letter characters
$name = preg_replace($pattern_name,'',$name);
$errors['name'] = 'Invalid characters found and removed in name';
}
Using either of these patterns does not work:
$pattern_name = '/[^a-zA-Z ?]/';
$pattern_name = '/[^a-zA-Z] ?/';
Expected result is a match, since 2 space characters exists in $name, thus the if-statement should be true and the replace function will update $name so its value will become "too longname".
You'll have to make your pattern more explicit. If you can have one space at maximum, and it must be surrounded by letters, then:
$pattern_name = '/^[a-z]+( [a-z]+)?$/i';
It should be as simple as adding a space in the brackets.
$pattern_name = '/[^a-zA-Z ]/';
I'd invert the regex, and instead of trying to find invalid characters, match valid names (is that what you are doing?). That gives us this regex: /[a-zA-Z]+ [a-zA-Z]+/. Match valid characters, one space and then more valid characters.