Hi guys,

I would like to validate some form input, and only allow the folowing:

letters, numbers, /, -
if(!preg_match("*[0-9A-Za-z,-,/]", $url_key)){
$erros[1] = '<small>Error submitting url key!</small>';
}

Which is not working..

Its not the point only to allow one / or -
But only letters, numbers and /- in the desired string length wanted by the user.

I have not used preg_match, regex'es much before - so i hope someone can point this out.

What is wrong in the way I begin the pattern, and end it etc etc?

I Hope someone can make me a bit more clever on this :-)

Regards Jan

Recommended Answers

All 6 Replies

if(!preg_match("~[0-9A-Za-z-/]+~", $url_key)) {}

The ~ marks the begin and end of the regex (any 2 matching chars). You do not need a comma to separate the items. The + says it has to be one or more of the preceding characters.

I forgot to mention that it needs to start with a slash / and only contain lower case letters and numbers too and the spacial chars as / _ - :-)

if(!preg_match([a-z][0-9][-/_], $url_key)){
$error[1] =  '<small>Error submitting url key!</small>';
}

So if i want it to begin with a slash, and then after that only allow lower case letters, numbers, dash and slash..
I understood preg_match returns 1 or 0, for false or true:

if(preg_match("/^[/][a-z0-9-/]+$/", $url_key)==0) {
echo 'error';
}

But that throws me this error:
Warning: preg_match() [function.preg-match]: Unknown modifier ']' in C:\blah blah..

Am I completely on the wrong track?

THIS PATTERN DOESNT GIVE ME AN ERROR WHEN I WRITE SPACIAL CHARS THAT ARE NOT SUPPPOSED TO BE ALLOWED:

if(!preg_match("~[0-9a-z-/]+~", $url_key)){echo 'error';}

If i entered lets say: **url/ ^^^#¤#\"" - then I get no error even though there are weird chars in, hmm

Because you used a slash as begin/end terminator, it means you will have to escape it, if you need to use it in the pattern (with a backslash).

Thank you for helping out pritaeas!

With this one:

if(!preg_match("~[0-9a-z-/]+~", $url_key)) {..}

I can write anything as long as there is either a number, a lowercase letter or a slash or a dash.

So this goes through the validation, with the above preg_match because of the slash at the end:
***^^!"#"!¤%&¤#/

How can I adjust that, so that it only allows what is written in the preg_match? So this ***^^!"#"!¤%&¤#/ would fail?

Use the start and end markers ^ and $

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.