How to use PHP regular expression to verify whether the input string is in English name format

WBOY
Release: 2023-06-24 15:46:02
Original
1006 people have browsed it

In PHP development, sometimes you need to verify whether an input string is in English name format. At this time, you can use regular expressions to achieve this.

What is the English name format? Generally speaking, the English name format contains English letters and spaces. There are one or more spaces between the last name and the first name, and the first letter needs to be capitalized. For example, John Smith.

So how to use PHP regular expressions to verify whether a string conforms to this format?

First, we can use the preg_match function to match. The first parameter of this function is the regular expression to be matched, and the second parameter is the string to be matched. The specific code is as follows:

$pattern = "/^[A-Z][a-z]+s[A-Z][a-z]+$/";
$string = "John Smith";
if (preg_match($pattern, $string)) {
    echo "匹配成功";
} else {
    echo "匹配失败";
}
Copy after login

In the above code, we defined a $pattern variable to store the regular expression. The regular expression contains:

  • ^ means matching the input characters The beginning of the string
  • [A-Z] means matching any uppercase letters
  • [a-z] means matching any lowercase letters
  • means matching the previous element one or more times
  • s means matching any whitespace characters, including spaces, tabs, newlines, etc.
  • $ means matching the end of the input string

Then we define a $string Variable to store the string to be matched, in this case "John Smith".

Finally, we use the preg_match function to match whether the string matches the English name format defined in the regular expression. If the match is successful, "match successfully" is output, otherwise "match failed" is output.

It should be noted that in actual development, we may need to support more formats, such as allowing middle names, allowing the use of hyphens, etc. In this case, the regular expressions need to be modified accordingly.

The above is the detailed content of How to use PHP regular expression to verify whether the input string is in English name format. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!