如何使用preg_match检查我的字符串是否包含空格?

时间:2010-10-14 20:12:42

标签: php regex

我在php中使用此代码来检测字符串是否包含a-z,A-Z,0-9以外的字符。我想检查字符串是否包含任何空格。我应该在模式中添加什么?

if (preg_match ('/[^a-zA-Z0-9]/i', $getmail)) {
    // The string contains characters other than a-z and A-Z and 0-9
}

3 个答案:

答案 0 :(得分:8)

如果要为当前模式添加空间,实际上需要在模式中输入空格:

/[^a-z0-9 ]/i
         ^
      Notice the space there

答案 1 :(得分:4)

你可以试试这个

/[^a-z0-9\s]/i

使用i修饰符时,不需要A-Z\s部分将表示空格,但也表示制表符或任何空格。

答案 2 :(得分:2)

if (preg_match('/[^a-z0-9 ]/i', $getmail)) // The string contains characters other than a-z (case insensitive), 0-9 and space

注意我已经从字符类中删除了A-Z,因为您已启用不区分大小写。