[英]How to check, if a php string contains only english letters and digits?
在JS中我使用了這段代碼:
if(string.match(/[^A-Za-z0-9]+/))
但我不知道,如何在PHP中做到這一點。
使用preg_match() 。
if (!preg_match('/[^A-Za-z0-9]/', $string)) // '/[^a-z\d]/i' should also work.
{
// string contains only english letters & digits
}
if(ctype_alnum($string)) {
echo "String contains only letters and numbers.";
}
else {
echo "String doesn't contain only letters and numbers.";
}
例如,您可以使用preg_match()函數。
if (preg_match('/[^A-Za-z0-9]+/', $str))
{
// ok...
}
看看這個快捷方式
if(!preg_match('/[^\W_ ] /',$string)) {
}
class [^\\W_]
匹配任何字母或數字但不匹配下划線。 請注意!
符號。 它將使您免於掃描整個用戶輸入。
if(preg_match('/[^A-Za-z0-9]+/', $str)) {
// ...
}
如果你需要檢查它是否是英語。 你可以使用以下功能。 可能會幫助別人..
function is_english($str)
{
if (strlen($str) != strlen(utf8_decode($str))) {
return false;
} else {
return true;
}
}
if(preg_match('/^[A-Za-z0-9]+$/i', $string)){ // '/^[A-Z-a-z\d]+$/i' should work also
// $string constains both string and integer
}
胡蘿卜是在錯誤的地方所以它會搜索除了方括號內的所有東西。 當胡蘿卜在外面時,它會搜索方括號中的內容。
PHP可以使用preg_match(regex, string)
將字符串與正則表達式進行比較preg_match(regex, string)
如下所示:
if (!preg_match('/[^A-Za-z0-9]+/', $string)) {
// $string contains only English letters and digits
}
if (preg_match('/^[\w\s?]+$/si', $string)) {
// input text is just English or Numeric or space
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.