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.
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 have written the following code to check if the given string is Latin or it contains some other non-latin chars like Persian. The issue is that it always returns true for both of the following strings:
$str = "Hello, What's up?"
Or
$str = "Hello, سلام"
While for the second string it should return false since it contains Persian characters (non-latin) too.
$default_rule = "/[a-zA-Z0-9\(\)\*_\-\!\#\$\%\^\&\*\,\.\"\'\]\[]*/";
$rule = ($rule==null) ? $default_rule : $rule;
if(preg_match($rule, $str)==true)
{
// always returns true
}
Your pattern will return true if the string contains zero or more of those characters you've specified. In other words, it will return true for any string at all. You need to put start (^) and end ($) anchors around it. Also you don't need to escape most of those characters (the character class causes them to be treated as literal characters):
$default_rule = '/^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]*$/';
But, this will match an empty string. To also make sure that the string is not empty, use the + quantifier (one or more) instead of *.
$default_rule = '/^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]+$/';
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';
}
I need a regex to see if the $input ONLY contained alphabetic characters or white spaces also need one to check if $numInput ONLY contained numeric characters or white spaces AND one combined so:
$alphabeticOnly = 'abcd adb';
$numericOnly = '1234 567';
$alphabeticNumeric = 'abcd 3232';
So in all of the above examples alphabetic, numeric, whitespace are allowed ONLY NO symbols.
How can I get those 3 diffrent regular expression?
This should help you
if (!preg_match('/^[\sa-zA-Z]+$/', $alphabeticOnly){
die('alpha match fail!');
}
if (!preg_match('/^[\s0-9]+$/', $numericOnly){
die('numeric match fail!');
}
if (!preg_match('/^[\sa-zA-Z0-9]+$/', $alphabeticNumeric){
die('alphanumeric match fail!');
}
This is pretty basic
/^[a-z\s]+$/i - letter and spaces
/^[\d\s]+$/ - number and spaces
/^[a-z\d\s]+$/i - letter, number and spaces
Just use them in preg_match()
In order to be unicode compatible, you should use:
/^[\pL\s]+$/ // Letters or spaces
/^[\pN\s]+$/ // Numbers or spaces
/^[\pL\pN\s]+$/ // Letters, numbers or spaces
I'm looking for a php preg replace to null/empty string if string contains any non alphanumeric characters or spaces
e.g. Strings
$string = "This string is ok";
$string = "Thi$ string is NOT ok, and should be emptied"
When I say emptied/nulled I mean it will make the string "".
So basically anything a-z A-Z 0-9 or space is ok
Any ideas?
if(preg_match('~[^a-z0-9 ]~i', $str))
$str = '';
You can use this pattern (note the possessive quantifier) to match "invalid" strings:
^[a-zA-Z0-9 ]*+.+$
Here's a snippet:
<?php
$test = array(
"This string is ok",
"Thi$ string is NOT ok, and should be emptied",
"No way!!!",
"YES YES YES"
);
foreach ($test as $str) {
echo preg_replace('/^[a-zA-Z0-9 ]*+.+$/', '<censored!>', $str)."\n";
}
?>
The above prints (as seen on ideone.com):
This string is ok
<censored!>
<censored!>
YES YES YES
It works by using possessive repetition (i.e. no backtracking) to match as many valid characters as possible with [a-zA-Z0-9 ]*+. If there's anything left after this, i.e. .+ matches, then we must have gotten stuck at an invalid character, so the whole string gets matched (and thus replaced). Otherwise the string remains untouched.
The string '<censored!>' is used as replacement here for clarity; you can use the empty string '' if that's what you need.
References
regular-expressions.info/Possessive Quantifier