Jump to content

[SOLVED] Whole string can be only alphanumeric and spaces


Recommended Posts

On my Login system, a valid username can contain letters, numbers and spaces. Since ereg will be removed in PHP 6 I'm making it with preg_match.

 

<?php

$pattern = "#^[A-Z0-9 ]$#i";

print preg_match ($pattern, "my username") ? "True" : "False";

?>

 

It always says false. It's probably something minor that's wrong.

You were very close Jordan :) welcome to preg!

 

Two notes. It is more common to use lowercase in patterns (even though with the i modifier, it doesn't matter.. just from common notation, [a-z] as opposed to [A-Z].. but again, this is nothing really.. it still functions as is.. but as for your space in the pattern, I would use \s.. this just makes it more readable from a coder's standpoint.. with an actual space, it feels like something's missing... I'm not sure if there are some actual potential problems with an actual space as opposed to specifying a space as \s (from other locales / unicodes and what not).

 

$pattern = '#^[a-z0-9\s]+$#i';

 

But glad to see you attempting preg.. hope it's starting to become more comfortable for you.

The downside to using \s is that it encompasses all whitespace. This includes spaces, form feeds, new lines, carriage returns, horizontal tabs, and vertical tabs. If you prefer to not see a blank space, you can use \x20.

 

 

you can use \x20.

 

Like this?

 

$pattern = '#^[a-z0-9\x20]+$#i';

 

You were very close Jordan :) welcome to preg!

 

[Words]

 

But glad to see you attempting preg.. hope it's starting to become more comfortable for you.

 

I'm starting to understand the basics of regular expressions.

The downside to using \s is that it encompasses all whitespace. This includes spaces, form feeds, new lines, carriage returns, horizontal tabs, and vertical tabs. If you prefer to not see a blank space, you can use \x20.

 

Ah, I forgot about that tidbit (I now remember reading that in the mastering expressions book). I must be more mindful of those kind of things.. I'll have to memorize '\x20' for usage of strict spaces only from here on in.

 

Good call (as usual  ;) )

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.