2016-09-16 272 views
0

我使用PHP,我需要检查是否是由刚刚如何检查字符串是否只包含英文字母?

  • 英文小写字母
  • 破折号
  • 下划线的字符串?

事情是这样的:

if (/* the condition */) { 
    // Yes, all characters of the string are English lowercase letters or dash or underline 
} else { 
    // No, there is at least one unexpected character 
} 

下面是一些例子:

$str = "test"; // true 
$str = "test_-'; // true 
$str = "t-s"; // true 
$str = "test1"; // false 
$str = "Test"; // false 
$str = "test?"; // false 
+2

'^ [A-Z _-] + $'应该为你做 – vks

+0

你指的是被称为[基本拉丁语(HTTPS字母:// EN。 wikipedia.org/wiki/ISO_basic_Latin_alphabet)字母。许多字符集还有用于英文文本的其他字母(其中包括带有音调符号的英文字母字符,撇号,重音符号,cedillas,连字符以及某些字符集中的某些撇号等等)。 –

回答

1

要匹配整个字符串,只包含1个或多个小写ASCII字母,连字符或下划线使用

/^[-a-z_]+$/D 

regex demo

详细

  • ^ - 字符串的开始
  • [-a-z_]+ - 1个或多个ASCII小写字母,连字符或下划线
  • $ - 串
  • /D - 修饰符是会使$匹配非常结束的字符串(否则,$也将匹配出现在字符串末尾的换行符)。

PHP:

if (preg_match('/^[-a-z_]+$/D', $input)) { 
    // Yes, all characters of the string are English lowercase letters or dash or underline 
} else { 
    // No, there is at least one unexpected character 
} 
+0

upvoted ...我想你想成为第一个正则表达式顶级用户';-)' –

+1

我没有尝试任何东西,只是试图遵循[*在阅读某人对你的问题的答案后你应该做的第一件事是投票在答案上,就像任何其他用户(具有足够的声誉)一样。投票答案是有帮助和经过充分研究的,并且回答不是的答案。其他用户也将对您的问题*](http://stackoverflow.com/help/someone-answers)指导方针进行投票。顺便说一句,我(几乎)总是upvote我回答的问题。 –

1

使用PHP函数

preg_match() 

与此正则表达式:

$regex = [a-z\_\-]+ 

\要逃避下划线和短划线。 +意味着你必须至少有1个字符。

这是正则表达式的方便工具http://www.regexpal.com/

1

试试这个关于大小

/** 
* Test if a string matches our criteria 
*/ 
function stringTestOk($str) { 
    return !(preg_match_all('/[^a-z_\-]/', $str) > 0); 
}  

// Examples 
foreach(['test', 'test_-', 't-s', 'test1', 'Test', 'test?'] as $str) { 
    echo $str, ' ', (stringTestOk($str) ? 'true' : 'false'), PHP_EOL; 
} 
相关问题