我将如何检测字符串中的空格?例如,我有一个名称字符串,如:
“简·多伊”
请记住,我不想修剪或替换它,只需检测第一个和第二个字符串之间是否存在空格。
按照 Josh 的建议使用 preg_match :
<?php
$foo = 'Bob Williams';
$bar = 'SamSpade';
$baz = "Bob\t\t\tWilliams";
var_dump(preg_match('/\s/',$foo));
var_dump(preg_match('/\s/',$bar));
var_dump(preg_match('/\s/',$baz));
输出:
int(1)
int(0)
int(1)
您可以只检查字母数字字符,而空格不是。你也可以为空间做一个 strpos 。
if(strpos($string, " ") !== false)
{
// error
}
不会preg_match("/\s/",$string)工作吗?与 strpos 相比,它的优势在于它会检测任何空格,而不仅仅是空格。
你可以使用这样的东西:
if (strpos($r, ' ') > 0) {
echo 'A white space exists between the string';
}
else
{
echo 'There is no white space in the string';
}
这将检测一个空格,但不会检测任何其他类型的空格。
<?php
if(strpos('Jane Doe', ' ') > 0)
echo 'Including space';
else
echo 'Without space';
?>
// returns no. of matches if $str has nothing but alphabets,digits and spaces.
function is_alnumspace($str){
return preg_match('/^[a-z0-9 ]+$/i',$str);
}
// returns no. of matches if $str has nothing but alphabets,digits and spaces. function
is_alnumspace($str) {
return preg_match('/^[A-Za-z0-9 ]+$/i',$str);
}
// This variation allows uppercase and lowercase letters.