views:

1298

answers:

6

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.

+1  A: 

You could check for only alphanumerical characters, which whitespace is not. You could also do a strpos for a space.

if(strpos($string, " ") !== false)
{
   // error
}
Chacha102
You want it like strpos($string, " ") instead. Haystack first, then needle
Terw
Keep in mind this will only detect spaces, not \r \t \n etc
Josh
Isn't \t a whitespace?
niteria
As stated by Josh, this is not a valid answer to the OP question. The OP wanted to detect "whitespace" not "spaces".
hobodave
The author's name is even "lacking preg_match". LOL.
Josh
sorry guys. i meant spaces. thought whitespace was equal to space.
lackingpregmatch
Why couldn't they standardize how needle/haystack functions take arguments. Should always have one first.
Chacha102
@Terw I fixed it in my answer
Chacha102
A: 

http://php.net/strpos

Ilya Biryukov
Invalid answer, cannot detect "whitespace" with strpos without using multiple function calls.
hobodave
A: 

http://no.php.net/strpos

<?php
if(strpos('Jane Doe', ' ') > 0)
    echo 'Including space';
else
    echo 'Without space';
?>
Terw
This won't work if the first character is a space - " > 0" should be " !== false"
Greg
I know, did it like that because it looked like he wanted to see if it was multiple names, not " Name" ;)
Terw
+2  A: 

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

Josh
I have a fear that if I call on my regex engine for something like finding a single character it will get mad at me and start outputting profanity :(
Kai
Maybe you don't feed it enough! ;-)
Josh
+3  A: 

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)
hobodave
Ha! I suggest it, you get upvoted :-) You were first to provide a real example tho...
Josh
Ha, yea. I always go for concrete examples if noone has provided one already. Too bad the OP seems to have selected the above as his answer :-\
hobodave
i guess i've always considered whitespace the space as space unless your using html entities.
lackingpregmatch
Ah, thanks for the Answer anyway. :)
hobodave
A: 
// 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);
}
Rachel