PHP - detect whitespace between strings

2019-01-11 16:31发布

How would I go about detecting whitespace within a string? For example, I have a name string like:

"Jane Doe"

Keep in mind that I don't want to trim or replace it, just detect if whitespace exists between the first and second string.

7条回答
何必那么认真
2楼-- · 2019-01-11 16:58

You may use something like this:

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

This will detect a space, but not any other kind of whitespace.

查看更多
小情绪 Triste *
3楼-- · 2019-01-11 17:01
// 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.
查看更多
聊天终结者
4楼-- · 2019-01-11 17:03

Use preg_match as suggested by Josh:

<?php

$foo = "Dave Smith";
$bar = "SamSpade";
$baz = "Dave\t\t\tSmith";

var_dump(preg_match('/\s/',$foo));
var_dump(preg_match('/\s/',$bar));
var_dump(preg_match('/\s/',$baz));

Ouputs:

int(1)
int(0)
int(1)
查看更多
虎瘦雄心在
5楼-- · 2019-01-11 17:05

Wouldn't preg_match("/\s/",$string) work? The advantage to this over strpos is that it will detect any whitespace, not just spaces.

查看更多
趁早两清
6楼-- · 2019-01-11 17:09
// 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);
}
查看更多
贼婆χ
7楼-- · 2019-01-11 17:16

http://no.php.net/strpos

<?php
if(strpos('Jane Doe', ' ') > 0)
    echo 'Including space';
else
    echo 'Without space';
?>
查看更多
登录 后发表回答