Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate string against regex

Tags:

regex

php

I'd like to validate file paths with a regular expression. So far I've come up with this:

preg_match('/[^A-Za-z0-9\.\/\\\\]/', $string);

so it will return 1 if the string has any other characters than A-Z, a-z, 0-9, dot, \ and /

How can I make it so it also returns 1 if there are more than two dots in the string, or if the dot is at the end of the string?

And how can I allow : but only if it's present as the 2nd character and followed by \ or /. For example c:\file should be valid

like image 267
Alex Avatar asked May 09 '13 18:05

Alex


1 Answers

For the first two requirements:

preg_match('/[^A-Za-z0-9\.\/\\\\]|\..*\.|\.$/', $string);

The \..*\. will match if there are more than two dots. \.$ will match if there is a dot at the end. By separating each of these portions (including your original regex) with a | it will make it so the regex will match any one of the expressions (this is called alternation).

The last requirement is a little tricky, since if I understand correctly you need this to return 1 if there is a :, unless the only colon is the second character and it is followed by a \ or /. The following regex (as a PHP string) should do that:

'/:(?!(?<=^[a-zA-Z]:)[\/\\\\])/'

Or combined with the other regex (note that we also have to add : to the first character class):

preg_match('/[^A-Za-z0-9\.\/\\\\:]|\..*\.|\.$|:(?!(?<=^[a-zA-Z]:)[\/\\\\])/', $string);

Here is the explanation for that last piece:

:                  # match a ':'
(?!                # but fail if the following regex matches (negative lookahead)
   (?<=^[a-zA-Z]:)   # the ':' was the second character in the string
   [\/\\\\]          # the next character is a '/' or '\'
)                  # end lookahead
like image 184
Andrew Clark Avatar answered Oct 09 '22 16:10

Andrew Clark