I need to validate a user text entry for a directory based on Windows, there is no directory picker of sort, it is just a text field.
I have written the following Regex using http://regex101.com/ which works adequately for my needs:
^[a-zA-Z]\:[\/,\\].{1,}
Which will match for example the following directories in the online tool:
C:/Users/Charlie/Dropbox
D:/Users/Bob/Quotes
F:/Quotes
The problem is, when using it in my application, preg_match
does not match any of the above. It does not return true, and the preg_last_error()
returns 0
which also indicates a false return value.
The exact code used is:
if(preg_match('/^[a-zA-Z]\:[\/,\\].{1,}/', $directory)) { }
Any help much appreciated.
You need to use quadruple backslash to match a literal backslash here:
if(preg_match('/^[a-zA-Z]\:[\/,\\\\].{1,}/', 'C:/Users/Charlie/Dropbox')) {
// ^^^^
See IDEONE demo
Otherwise, the backslash is just escaping the ]
and that ruins the regex character class.
Note that instead of {1,}
you can just use +
quantifier that means 1 or more occurrences and that you do not have to escape the colon.
I also do not understand why you have a comma in the character class, the character is treated as a literal. I think you just want to match either \\
or /
with [\\/,\\\\\\]
? Then, the whole regex would look like
'/^[a-zA-Z]:[\/\\\\].+/'
See another demo
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.