我将如何使用 PHP 函数 preg_match() 来测试字符串以查看是否存在空格?
例子
“这句话将对空格进行测试”
“thisOneWouldTestFalse”
我将如何使用 PHP 函数 preg_match() 来测试字符串以查看是否存在空格?
“这句话将对空格进行测试”
“thisOneWouldTestFalse”
如果您对任何空白(包括制表符等)感兴趣,请使用\s
if (preg_match("/\\s/", $myString)) {
// there are spaces
}
如果您只对空间感兴趣,那么您甚至不需要正则表达式:
if (strpos($myString, " ") !== false)
另请参阅解决此问题的StackOverflow 问题。
而且,根据您是否要检测制表符和其他类型的空白,您可能需要查看诸如 \b \w 和 [:SPACE:] 之类的 perl 正则表达式语法
您可以使用:
preg_match('/[\s]+/',.....)
[\\S]
大写 - 'S' 肯定会起作用。
为此目的使用 ctype_graph 怎么样?这将扩大空间的范围,以表示任何“空白字符”也不会打印屏幕上可见的任何内容(如 \t, \n )。然而,这是原生的,应该比 preg_match 更快。
$x = "string\twith\tspaces" ;
if(ctype_graph($x))
echo "\n string has no white spaces" ;
else
echo "\n string has spaces" ;
使用更快:
strstr($string, ' ');
我们还可以使用以下表达式检查空格:
/\p{Zs}/
function checkSpace($str)
{
if (preg_match('/\p{Zs}/s', $str)) {
return true;
}
return false;
}
var_dump((checkSpace('thisOneWouldTestFalse')));
var_dump(checkSpace('this sentence would be tested true for spaces'));
bool(false)
bool(true)
如果您希望简化/更新/探索表达式,它已在regex101.com的右上角面板中进行了说明。如果您有兴趣,可以在此调试器链接中观看匹配步骤或修改它们。调试器演示了 RegEx 引擎如何逐步使用一些示例输入字符串并执行匹配过程。