Using a Regular Expression in PHP to validate a name - php

Here i want to validate a name where:
A name only consist of these characters [a-zA-Z-'\s]
however a sequence of two or more of the hyphens or apostrophe can not exist
also a name should start with a letter.
I tried
$name = preg_match("/^[a-zA-Z][a-zA-Z'\s-]{1,20}$/", $name);
however it allows double hyphens and apostrophes.
If you can help thank you

You can invalidate names containing a sequence of two or more of the characters hyphen and apostrophe by using a negative lookahead:
(?!.*['-]{2})
For example
$names = array('Mike Cannon-Brookes', "Bill O'Hara-Jones", "Jane O'-Reilly", "Mary Smythe-'Fawkes");
foreach ($names as $name) {
$name_valid = preg_match("/^(?!.*['-]{2})[a-zA-Z][a-zA-Z'\s-]{1,20}$/", $name);
echo "$name is " . (($name_valid) ? "valid" : "not valid") . "\n";
}
Output:
Mike Cannon-Brookes is valid
Bill O'Hara-Jones is valid
Jane O'-Reilly is not valid
Mary Smythe-'Fawkes is not valid
Demo on 3v4l.org

Related

Explode surname and name by lower/upper

How can I separate firstname and surname from a string like this:
Pietro DE GIOVANNI
(Pietro being the firstname and DE GIOVANNI the surname)
I used to do it with an explode() on the spaces, but obviously it doesn't work on a person like that.
Thanks in advance.
You can explode on the names by spaces as before, then loop the result as individual pieces of the name. Check with ctype_upper() if the string is purely uppercase or not, and append it to the proper variable.
Putting it into a function, it may look like this
function split_name($fullname) {
$firstname = "";
$surname = "";
$pieces = explode(" ", $fullname);
foreach ($pieces as $name) {
if (ctype_upper($name))
$surname .= $name." ";
else
$firstname .= $name. " ";
}
return array("firstname" => $firstname, "surname" => $surname);
}
You can then use it as such
$name = "Pietro DE GIOVANNI";
$split = split_name($name);
echo "Firstname: ".$split['firstname']."\nSurname: ".$split['surname'];
Note
This doesn't work for names such as James O'RILEY, John-Paul JOHNSON or John. F. KENNEDY. The first two we can circumvent by stripping away any characters that's not a-zA-Z before comparing with ctype_upper(), but the latter we won't be able to distinguish if it's a firstname or surname - there's not enough data to say either way. You can assume that it's always a part of the firstname (for instance), and/or check if it's after we've started looking at the surnames (if a name in capital letters has been found yet). You can take care of the first two cases by checking for
if (ctype_upper(filter_var(str_replace("'", "", $name), FILTER_SANITIZE_STRING)))
instead of using the if statement in the original codeblock. This removes quotes and any non-a-zA-Z values.
Here's a live demo where I've stripped away names that contain any characters beside a-zA-Z, which would account for the two first issues.

How to Search for Space in Php String?

I'd like to know How to Search for Space in Php
For example , I've got $Studentname and it's value is John Green . I want to have $Name (with value John) And $Surname(With value Green) . But i don't know how to search space in string .
Thanks in advance
Using explode() without a limit will result in incorrect results. Some first and last names have spaces. For example:
$name = explode(" ","Jan Van Riebeck");
echo $name[0]." ".$name[1]; // Jan Van (incorrect)
$name = explode(" ","St. John Westcox");
echo $name[0]." ".$name[1]; // St. John (incorrect)
Use explode() with a limit (so it only returns 2 items), like so:
$name = explode(" ","Jan Van Riebeck",2);
echo $name[0]." ".$name[1]; // Jan Van Riebeck (correct)
This will still be incorrect some time, but more last names have spaces than first names. Ideally, if you're capturing the form data, use two different fields for first and last name, but even this isn't always ideal, some cultures have different ways that names work that aren't as simple as first name last name.
Here is a list of common pitfalls when it comes to working with names
First suggestion:-
Try to take first name and last name in two different fields when you are using html form.
Use below code if the above not possible:-
<?php
$Studentname = 'John Green';
$student_full_name = explode(' ',trim($Studentname));//trim to remove space from starting and ending and explode to break string when space found
$first_name = $student_full_name[0];//output John
$sur_name = $student_full_name[1];//output Green
?>
Note:- What happen if a user put name like "John Green smith" Or "John(more than one space)Green". That's why do first point.
You can use the explode() function to split a string into an array by using the space as a delimiter:
$names = explode(" ", "John Smith");
However, you might want to take account of people doing silly things like putting double spaces between the first name and last name, or having preceding or trailing spaces.
You can use trim() for getting rid of trailing and preceding spaces:
$fullName = " John Smith ";
$trimmedName = trim($fullName); // Assigns "John Smith"
You can also use preg_replace() to get rid of multiple spaces between the first and last name:
$fullName = "John Smith";
$cleanedName = preg_replace("/\s+/", " ", $fullName); // Assigns "John Smith"
The above code will replace one or more (+) consecutive spaces (\s) with a single space.
to get name and username from student name follow this
$Studentname = 'John Green';
$name = explode(' ',$Studentname);
$firstname = $name[0]; //output john
$lastname = $name[1]; //output green

make uppercase the first letter of name [duplicate]

This question already has answers here:
How to make first letter of a word capital?
(5 answers)
Closed 7 years ago.
I have a variable like
$fullname = "dwayne-johnson";
How can I make the "d" of the first letter of the word dwayne and the "j" of the word johnson? like I want to make uppercase the first letter of the every word that is separated by dash, for example I have following variable (refer below)
$fullname1 = "dwayne-johnson" //expected result is, Dwayne Johnson
$fullname2 = "maria-osana-makarte" //expected result is, Maria Osana Makarte
as you can see from above the variable fullname1 have 2 words separated by dash and so the first letter in both words are capitalized. The second variable $fullname2 has 3 words separated by dash and so the first letter of each words within that variable is been capitalized. So how to make it capitalize the first letter of each words that is separated by dash in variable? Any clues, ideas, suggestions, help and recommendations is greatly appreciated. Thank you.
PS: i have already a function that convert the dash to space so now all I have to do is to make the first letter of every words that is separated by dash within the variable and the after it has been capitalized I will then inject the dash-space function on it.
Try with -
$fullname1 = ucwords(str_replace('-', ' ', $fullname1));
You can use the ucword function
Here's an example:
<!DOCTYPE html>
<html>
<body>
<?php
echo ucwords("hello world");
?>
</body>
</html>
<?php $text = str_replace("-", " ", $fullname1);
echo ucwords($text);?>
You can use the following code
$fullname = "dwayne-johnson";
// replace dash by space
$nospaces = str_replace("-", " ", $fullname);
// use ucword to capitalize the first letter of each word,
// making sure that the input string is fully lowercase
$name = ucword(strtolower($nospaces));
<?php
$fullname = "dwayne-johnson";
$fullname_without_dash = str_replace("-"," ",$fullname); // gives -> "dwayne johnson"
$fullname_ucword = ucwords($fullname_without_dash); //gives -> "Dwayne Johnson"
echo $fullname_ucword;
?>

PHP preg_match regex to find letters numbers and spaces?

When people sign up to my site I validate their names with this code:
if (preg_match("[\W]", $name))
{
$mess = $mess . "Your name must contain letters only.<br>";
$status = "NOTOK";
}
This is because your actual name cannot contain symbols unless your parents were drunk when they named you.
However, this regex doesn't detect spaces. How can I fix it?
You can use the following regular expression:
^[\w ]+$
This matches any combinations of word characters \w and spaces , but as the guys said be careful because some names might contain other symbols.
So you can use it like this:
if (preg_match("/^[\\w ]+$/", $name)) {
// valid name
}
else {
// invalid name
}
Try this:
<?php
$user_input = 'User_name';
if (!preg_match('/^[a-z0-9_\s]+$/i', $user_input)) {
// Matches English letters, numbers underscores(_) and spaces
$mess = $mess . "Your name must contain letters only.<br>";
$status = "NOTOK";
}
?>
You just missed regexp separators. I do this sometimes even after 10 years of programming.
if (preg_match("/[\W]/", $name)) ...

Regex to allow A-Z, - and '

I am trying to get this Regex to work to validate a Name field to only allow A-Z, ' and -.
So far I am using this which is working fine apart from it wont allow an apostrophe.
if (preg_match("/[^a-zA-Z'-]+/",$firstname)) {
// do something
}
I would like it to only allow A-Z, - (dash) and an ' (apostrophe). It works for the A-Z and the - but still wont work for the '
Could someone please provide an example?
Thanks
if (preg_match("/^[A-Z'-]+$/",$firstname)) {
// do something
}
The caret ^ inside a character class [] will negate the match. The way you have it, it means if the $firstname contains characters other than a-z, A-Z, ', and -.
Your code already does what you want it to:
<?php
$data = array(
// Valid
'Jim',
'John',
"O'Toole",
'one-two',
"Daniel'Blackmore",
// Invalid
' Jim',
'abc123',
'$##$%##$%&*(*&){}//;;',
);
foreach($data as $firstname){
if( preg_match("/[^a-zA-Z'-]+/",$firstname) ){
echo 'Invalid: ' . $firstname . PHP_EOL;
}else{
echo 'Valid: ' . $firstname . PHP_EOL;
}
}
... prints:
Valid: Jim
Valid: John
Valid: O'Toole
Valid: one-two
Valid: Daniel'Blackmore
Invalid: Jim
Invalid: abc123
Invalid: $##$%##$%&*(*&){}//;;
The single quote does not have any special meaning in regular expressions so it needs no special treatment. The minus sign (-), when inside [], means range; if you need a literal - it has to be the first or last character, as in your code.
Said that, the error (if any) is somewhere else.
"/[^a-zA-Z'-]+/" actually matches everything but a-zA-z'-, if you put the ^ in to indicate the start-of-string, you should put it outside the brackets.
Also, the '- part of your expression is possibly being interpreted as a range, so you should escape the - as #Tom answered or escape the , as someone else answered
From what I see. Following Regex should work fine:
if (preg_match("/^[A-Z\'\-]+$/",$firstname)) {
// do something
}
Here I have escaped both apostrophe and dash. I have tested this in an online Regex tester and works just fine.
Give it a try
Your regexp should look like this:
preg_match("/^[A-Z\'-]+$/",$firstname);
maches: AB A-B AB-'
does not match: Ab a-B AB# <empty string>
if (preg_match("/^[a-zA-Z -]*$/", $firstname)) {
// do something here
}
I have used this, This will work fine. Use It.

Categories