使用preg_match匹配字符串

时间:2011-06-09 10:14:46

标签: php regex

我在$abc变量中有文字。

现在我想检查文本是否只能包含字符(a-z, A-Z, 0-9)。如果他们有除了那些之外的任何字符,那么应该返回“输出”。

我该怎么做?

example: $abc = "this is @ text"; // no match 

3 个答案:

答案 0 :(得分:6)

类似的东西:

$abc = "this is @ text";
if (!preg_match('/^[a-z0-9]*\z/i', $abc)) {
  echo 'bad';
}

关于Jame C的评论,这里是倒置的案例:

$abc = "this is @ text";
if (preg_match('/[^a-z0-9]/i', $abc)) {
  echo 'bad';
}

答案 1 :(得分:4)

if ( !preg_match('#^[a-zA-Z0-9]*$#', $abc) ) {
    // wrong chars spotted
}

答案 2 :(得分:2)

你应该能够评估

preg_match('/[^A-Za-z0-9]/', $myString)

如果您不介意空间和下划线也在那里,那么您可以使用它:

preg_match('/\W/', $myString)