PHP 检查字符串是否包含单词之间的空格(不在开头或结尾)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37142882/
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
PHP check if string contains space between words (not at beginning or end)
提问by Eddy Unruh
I need to check if a string contains a space between words, but not at beginning or end. Let's say there are these strings:
我需要检查一个字符串是否包含单词之间的空格,而不是开头或结尾。假设有这些字符串:
1: "how r u ";
2: "how r u";
3: " howru";
Then only 2
should be true. How could I do that?
那么才2
应该是真的。我怎么能那样做?
回答by Don't Panic
You can verify that the trimmed string is equal to the original string and then use strpos
to find a space.
您可以验证修剪后的字符串是否等于原始字符串,然后用于strpos
查找空格。
if ($str == trim($str) && strpos($str, ' ') !== false) {
echo 'has spaces, but not at beginning or end';
}
回答by Toto
If your string is at least two character long, you could use:
如果您的字符串至少有两个字符长,您可以使用:
if (preg_match('/^\S.*\S$/', $str)) {
echo "begins and ends with character other than space";
} else {
echo "begins or ends with space";
}
Where \S
stands for any character that is not a space.
Where\S
代表任何不是空格的字符。
回答by user3394825
you can acces letter in a array
您可以访问数组中的字母
for($i = 1 ; i < strlen($word)-1 ; $i++ )
{
if($word[$i] = " " ;
{
echo "space" ;
}
}