Home > Article > Backend Development > How to detect if a string has only letters in php
In php, you can use the preg_match() function with the regular expression "/^[a-zA-Z\s] $/" to detect whether a string has only letters. The syntax "preg_match("/^[a -zA-Z\s] $/",string)"; if the return value is 1, only letters are returned, if 0 is returned, other characters are included.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php detects whether the string only has letters, in other words That is: Determine whether the string is pure English letters
In PHP, you can use the preg_match() function with a regular expression to check.
## The #preg_match() function can search and match strings based on regular expressions. The syntax format of the function is as follows:Regular expression used: "
/^[a-zA-Z\s] $/
"
preg_match($pattern,$subject [, &$matches [, $flags = 0 [, $offset = 0 ]]])The parameter description is as follows:
<?php header('content-type:text/html;charset=utf-8'); echo preg_match("/^[a-zA-Z\s]+$/","abcddfkj")."<br>"; echo preg_match("/^[a-zA-Z\s]+$/","ab12kj"); ?>This kind of output is not very good. Let’s customize a function and do a process to return true if there are only letters. Otherwise return false
function is_english($str) { if(preg_match("/^[a-zA-Z\s]+$/",$str)){ return true; } return false; }Call the function to determine whether the string is composed of pure English letters
var_dump(is_english('php.cn')); // bool(false) 含有标点符号所以返回 false var_dump(is_english('phpcn')); // bool(true) var_dump(is_english('phpcn123')); // bool(false) 含有123 var_dump(is_english('欢迎来到这里')); // bool(false) 都是中文Recommended learning: "
PHP Video Tutorial》
The above is the detailed content of How to detect if a string has only letters in php. For more information, please follow other related articles on the PHP Chinese website!