PHP检查字符串是否包含单词之间的空格(不在开头或结尾)[关闭]

问题描述 投票:3回答:3

我需要检查字符串是否包含单词之间的空格,但不能包含开头或结尾的空格。假设有以下字符串:

1: "how r u ";
2: "how r u";
3: " howru";

然后只有2应该为true。我该怎么办?

php string preg-match
3个回答
17
投票
if ($str == trim($str) && strpos($str, ' ') !== false) { echo 'has spaces, but not at beginning or end'; }

4
投票
if (preg_match('/^\S.*\S$/', $str)) { echo "begins and ends with character other than space"; } else { echo "begins or ends with space"; }

\S代表不是空格的任何字符。


-2
投票
for($i = 1 ; i < strlen($word)-1 ; $i++ ) { if($word[$i] = " " ; { echo "space" ; } }
© www.soinside.com 2019 - 2024. All rights reserved.