php 如何使用 preg_match 测试空格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1384965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I use preg_match to test for spaces?
提问by kylex
How would I use the PHP function preg_match() to test a string to see if any spaces exist?
我将如何使用 PHP 函数 preg_match() 测试字符串以查看是否存在空格?
Example
例子
"this sentence would be tested true for spaces"
"thisOneWouldTestFalse"
“这句话将被测试为正确的空格”
“thisOneWouldTestFalse”
回答by nickf
If you're interested in any white space (including tabs etc), use \s
如果您对任何空白区域(包括制表符等)感兴趣,请使用 \s
if (preg_match("/\s/", $myString)) {
// there are spaces
}
if you're just interested in spaces then you don't even need a regex:
如果您只对空格感兴趣,那么您甚至不需要正则表达式:
if (strpos($myString, " ") !== false)
回答by JYelton
Also see this StackOverflow questionthat addresses this.
另请参阅解决此问题的 StackOverflow 问题。
And, depending on if you want to detect tabs and other types of white space, you may want to look at the perl regular expression syntax for things such as \b \w and [:SPACE:]
而且,根据您是否要检测制表符和其他类型的空格,您可能需要查看 perl 正则表达式语法,例如 \b \w 和 [:SPACE:]
回答by Nagy Zoltan
You can use:
您可以使用:
preg_match('/[\s]+/',.....)
回答by Avisek Chakraborty
[\S]
upper case- 'S' will surely work.
大写 - 'S' 肯定会工作。
回答by rjha94
How about using ctype_graph for this purpose? This would expand the scope of space to mean any "white space char" that does not print anything visible on screen (like \t, \n ) also. However this is native and should be quicker than preg_match.
为此目的使用 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" ;
回答by danielpopa
faster to use:
使用更快:
strstr($string, ' ');
strstr($string, ' ');
回答by Emma
We can also check for spaces using this expression:
我们还可以使用这个表达式检查空格:
/\p{Zs}/
Test
测试
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'));
Output
输出
bool(false)
bool(true)
If you wish to simplify/update/explore the expression, it's been explained on the top right panel of regex101.com. You can watch the matching steps or modify them in this debugger link, if you'd be interested. The debugger demonstrates that how a RegEx enginemight step by step consume some sample input strings and would perform the matching process.
如果你想简化/更新/探索表达式,它已在regex101.com 的右上角面板中进行了解释。如果您有兴趣,可以在此调试器链接中观看匹配步骤或修改它们。调试器演示了 RegEx 引擎如何逐步使用一些示例输入字符串并执行匹配过程。

