i would like to know if i can check spaces between symbols in PHP.
because i want the username for a member in my site not to contain space.
for example:(joshua mwatu),this name contains space.
i would like the script to check if the username contains space and display error!
echo"The username shouldnot contain space";

I real dont know if i can do this .
Help please.

i guess you could use ctype_space() function for more details refer to php manual http://in.php.net/manual/en/function.ctype-space.php

else u cud do it more effectively using javascript --

function hasWhiteSpace(s) 
{

     reWhiteSpace = new RegExp(/^\s+$/);

     // Check for white space
     if (reWhiteSpace.test(s)) {
          alert("Please Check Your Fields For Spaces");
          return false;
     }
return true;
}

else u cud do it more effectively using javascript

That wouldn't be much use if javascript is disabled on the client, however. There should always be a hardcoded fallback method to rely on in that scenario.

if (preg_match('#\s+#', $username))
{
    [error notification here]
}

i guess you could use ctype_space() function for more details refer to php manual http://in.php.net/manual/en/function.ctype-space.php

ctype_space seems to check if the string is composed of all spaces.

I think the function to use would be ctype_graph.
http://in.php.net/manual/en/function.ctype-graph.php

This makes sure all characters are printable, and do not create whitespace.

So if the string contains space (\n) or tab (\n) or line breaks (\n) and (\r\n) on Win, then it will return false.

In addition to the regex examples posted:

if (preg_match('#\s+#', $username))
{
[error notification here]
}

You could also use strpos() and stristr().

eg:

if (strpos($string, ' ') !== false) {
// there is a space somewhere
}

http://in.php.net/manual/en/function.strpos.php

It would be faster then using regex.

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Comments
great tips
This article has been dead for over six months. Start a new discussion instead.