By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,664 Members | 1,643 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,664 IT Pros & Developers. It's quick & easy.

Validating Chars in a String

P: n/a
I'm looking in my PHP book but still figure out the best way to
validate that certain characters are contained in a string - for
example, when a user enters a username, I want to limit the characters
to a..z, A..Z,0..9 only. What's the best way to check for this?

Thanks...

Jul 16 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a
> if (!preg_match("#^([a-zA-Z0-9]+)$#", $useranme) {
die('Invalid chars in username!');
}


A friendlier method than the die would be, of course:

if (!preg_match("#^([a-zA-Z0-9]+)$#", $useranme) {
$error_message = "Invalid chars in username!";
}

echo ( $error_message != "" ) ?
"$error_message"
:
"$success_message or whatever the script does afterwards ...";

rudi

Jul 16 '05 #2

P: n/a
On Fri, 15 Aug 2003 19:27:55 +0200 in
<message-id:bh**********@svr8.m-online.net>
Rudolf Horbas <rh*****@hypotext.de> wrote:
if (!preg_match("#^([a-zA-Z0-9]+)$#", $useranme) {
die('Invalid chars in username!');
}


A friendlier method than the die would be, of course:

if (!preg_match("#^([a-zA-Z0-9]+)$#", $useranme) {
$error_message = "Invalid chars in username!";
}

echo ( $error_message != "" ) ?
"$error_message"
:
"$success_message or whatever the script does afterwards
...";

rudi

Naturally rudi.. mine was a quick demo example.. and I wouldn't
implement a plain die() call like that for a live application =)

Regards,

Ian

--
Ian.H [Design & Development]
digiServ Network - Web solutions
www.digiserv.net | irc.digiserv.net | forum.digiserv.net
Programming, Web design, development & hosting.
Jul 16 '05 #3

P: n/a
On Fri, 15 Aug 2003 14:18:11 GMT, "Ian.H [dS]" <ia*@WINDOZEdigiserv.net> wrote:
On Fri, 15 Aug 2003 13:32:31 GMT in
<message-id:08********************************@4ax.com>
Ralph Freshour <ra***@primemail.com> wrote:
I'm looking in my PHP book but still figure out the best way to
validate that certain characters are contained in a string - for
example, when a user enters a username, I want to limit the characters
to a..z, A..Z,0..9 only. What's the best way to check for this?


if (!preg_match("#^([a-zA-Z0-9]+)$#", $useranme) {
die('Invalid chars in username!');
}


Or just:

if (preg_match('/[^A-Za-z0-9]/', $username) {

No need to capture anything, so lose the brackets, and since you're looking
for bad characters it can return when it finds any, rather than scanning the
whole lot to make sure they're all good.

--
Andy Hassall (an**@andyh.co.uk) icq(5747695) (http://www.andyh.co.uk)
Space: disk usage analysis tool (http://www.andyhsoftware.co.uk/space)
Jul 16 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.