33

How would I go about detecting whitespace between strings? 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.

2

6 Answers 6

82

Use preg_match as suggested by Josh:

<?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));

Ouputs:

int(1)
int(0)
int(1)
Sign up to request clarification or add additional context in comments.

2 Comments

i guess i've always considered whitespace the space as space unless your using html entities.
if we talk about web, use the KISS method please, you don't want to start the regex engine just to justify lazyness
8

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

2 Comments

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 :(
Maybe you don't feed it enough! ;-)
8

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
}

6 Comments

You want it like strpos($string, " ") instead. Haystack first, then needle
As stated by Josh, this is not a valid answer to the OP question. The OP wanted to detect "whitespace" not "spaces".
The author's name is even "lacking preg_match". LOL.
sorry guys. i meant spaces. thought whitespace was equal to space.
Why couldn't they standardize how needle/haystack functions take arguments. Should always have one first.
|
5

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.

Comments

-1

http://no.php.net/strpos

<?php
if(strpos('Jane Doe', ' ') > 0)
    echo 'Including space';
else
    echo 'Without space';
?>

2 Comments

This won't work if the first character is a space - " > 0" should be " !== false"
I know, did it like that because it looked like he wanted to see if it was multiple names, not " Name" ;)
-1
// 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);
}

2 Comments

[a-z] does not cover alphabetic characters.
This answer has nothing to do with the asker's requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.