33

我将如何检测字符串中的空格?例如,我有一个名称字符串,如:

“简·多伊”

请记住,我不想修剪或替换它,只需检测第一个和第二个字符串之间是否存在空格。

4

7 回答 7

81

按照 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)
于 2009-07-21T21:07:19.697 回答
8

您可以只检查字母数字字符,而空格不是。你也可以为空间做一个 strpos 。

if(strpos($string, " ") !== false)
{
   // error
}
于 2009-07-21T20:59:58.043 回答
8

不会preg_match("/\s/",$string)工作吗?与 strpos 相比,它的优势在于它会检测任何空格,而不仅仅是空格。

于 2009-07-21T21:01:59.067 回答
5

你可以使用这样的东西:

if (strpos($r, ' ') > 0) {
    echo 'A white space exists between the string';
}
else
{
    echo 'There is no white space in the string';
}

这将检测一个空格,但不会检测任何其他类型的空格。

于 2011-08-09T06:28:12.467 回答
0

http://no.php.net/strpos

<?php
if(strpos('Jane Doe', ' ') > 0)
    echo 'Including space';
else
    echo 'Without space';
?>
于 2009-07-21T21:01:36.557 回答
0
// 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);
}
于 2010-03-16T15:12:00.843 回答
0
// 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.
于 2011-02-27T14:45:43.483 回答