Jump to content

No illegal characters?


Perad

Recommended Posts

The problem with the involvement of \w is that this also includes the underscore, as well as characters like é, à etc (depending on the locale from my understanding).

So the use \W, won't eliminate those characters (which falls outside of a-zA-Z0-9). jackpf, you're initial character would do it. One could also use:

 

#[^a-z0-9]#i

 

or one could make use of !ctype_alnum as well...

My bad on !ctype_alnum.. (as this includes characters like é...[perhaps again, locale dependent?]).

 

 

Wouldn't this be good?

preg_match('/\W/', $str, $match);
if (empty($match)) // all valid

 

You tell me ;)

$str = '123aBc_dé';
echo $str . "<br />\n";
echo (preg_match('/\W/', $str))? 'Does not only contain a-zA-Z0-9' : 'Does only contain a-zA-Z0-9';

 

 

 

And of course, both ctype_alnum and \w also include exponents (1E²7³). So from where I see it, the only difference I can tell between ctype_alnum and \w is that cytpe_alnum lacks support for underscore.. so in either case, I would personally stick to #[^a-z0-9]#i

 

Damn you, ctype_alnum! *shakes fist*

 

EDIT - I guess one would have to set the proper locale for the desired effect for cype_alnum.

preg_match('/\W/', $str, $match);

if (empty($match)) // all valid

I don't think that would work since $match would be an array. Idk if empty() checks arrays. If it does, forgive me.

 

If it doesn't, I think

preg_match('/\W/', $str, $match);
if (count($match) == 0) // all valid

would be better. Or not. Idk

If you want to do a check, why not use the return of the preg_match

 

Return Values

 

preg_match() returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject . preg_match() returns FALSE if an error occurred.

 

So...

 

preg_match('/\W/', $str, $match);
if (count($match) == 0) // all valid

 

Becomes:

if (preg_match('/\W/', $str, $match) > 0) // all valid

 

There is a reason they gave it a return value :)

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.