Regular Expression

Associate
Joined
26 Jun 2003
Posts
1,140
Location
North West
Im trying to make sure a user can only enter a string which has characters [a-zA-Z_0-9] (This eqivalent to '\w'?), but it seems to not work.

If the string only contains these characters do this, otherwise do that.

PHP:
if(!preg_match('\w', $string))
  postError;
else
  continue;

Can anyone see why is isnt working?
 
You're saying "If this string is a single whitespace character". So " " will not match. You need to match either a whitespace character that's surrounded by 0 or many other characters:
Code:
(.*?)\w(.*?)

or just match a string of characters you want 1 or many times:

Code:
[a-zA-Z0-9]+
 
PHP:
if (!preg_match('[a-zA-Z_0-9]+', $string))
{
// bla bla
}

Returns the following error:

Warning: preg_match() [function.preg-match]: Unknown modifier '+' in mypage.php on line 19
 
You need to put the expression between delimiters:
PHP:
if (!preg_match('|[a-zA-Z_0-9]+|', $string))
{
// bla bla
}
I used the pipe here, but you can use other characters like a # or a /.
 
No errors this time but this string was accepted:

23424\"\"%\"&\"\"

Any Ideas?

Im running the string through strip_tags first:

$string = strip_tags($_POST['variable']);

!preg_match(.....
 
\w means single word, no whitespace.

Code:
<?php

if (preg_match('/^[a-z0-9_]+$/im', $string))
{
    // $string only contains a-z, 0-9 chars (upper and lower)
}

?>
 
Back
Top Bottom