views:

67

answers:

4

Hi,

Recently i've switched to PHP 5.3+ and after that migration i learned that the eregi() function has been depreciated, its the function i mostly used for my regex needs.

But now i had to switch to preg_match() function, i am having trouble validating a certain condition.

Hello World

I want the preg_match to validate the above "hello world" string, the string contains whitespace in it.

But i want it to validate even if there is no whitespace "helloWorld" or just "hello".

What i'm trying to do is that in my script i have a text-field for the category title, i want it to accept spaces in it and no other special characters (such as ._-+*,).

I have made it to work but i'm not sure if thats the right way which i'm using.

preg_match('/^[a-zA-Z0-9\s]*$/', $cat_name);'

Any help would be appreciated.

+1  A: 

Yes, that is the correct way. You can also use an insensitive-case modifier instead of a-zA-Z:

preg_match('/^[a-z0-9\s]*$/i', $cat_name);'

One thing that you might want to consider is that your regular expression currently accepts the empty string. If you want to ensure that there is at least one character then use + instead of *.

Mark Byers
A: 

Note that \s also allows other space characters like tabulator or newline.

André Hoffmann
what else i could use other than the \s ?
Zubair1
just use a space instead: " "(without the brackets)
André Hoffmann
Use a simple space (' ') instead...that would work for spaces only, and not other whitespaces
Frxstrem
+4  A: 

Looks OK, but will accept empty string, so you can change * to + Remember that this regex will propably no accept language-specified UTF-8 chars.

See that comment in manual: http://www.php.net/manual/en/function.preg-match.php#95828

Also note, that some specific charaters are very often used in titles, like " and maybe it would better to allow it.

killer_PL
+1 because I also wrote that in my update to my answer, but I think you were 2 seconds faster. :)
Mark Byers
Thanks Killer_PL and Mark Byers :)I was actually checking for non-empty condition for this above this regex check.
Zubair1
lol i don't know how to post code in the comments here :) it shows messed up.
Zubair1
I have a if/else conditionif emptyelseif str_lenelseif preg_matchall the if statements throw a different error to the user.
Zubair1
+1  A: 

Should work, but you can replace the \s with a normal space " ", so it only matches spaces instead of other whitespace chars (like tabs). Also replace the * with + so it won't take empty strings.

preg_match('/^[a-z0-9 ]+$/i', $cat_name);'
Powertieke
Thanks, Done :)Would it still be a threat if i were to be checking for empty string before this preg_match? i'm still doing it just incase but was wondering :)
Zubair1
You shoudn't have to, but you can use different checks to return different error messages. Might be user-friendly to tell the user what he's doing wrong exactly :)
Powertieke