0

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.

4
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by digital-ether
0

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;
}
0

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]
}
1

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 by mike_2000_17: Fixed formatting

Votes + Comments
great tips
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.