I'm creating a regex that matches with Windows's filesystem file pathing:
c:\WINDOWS\SYSTEM32\cmd\a.php //valid match
c:\WINDOWS\SYSTEM32\cmd\a //invalid match
with this pattern and code:
function validate_filepath()
{
$view_path = 'c:\WINDOWS\SYSTEM32\cmd\a.php';
// ^(?:[\w]\:) # matching drive
//(?:\\[^\\:*?"<>|\r\n]+)+\\ # matching folder
// [^\\:*?"<>|\r\n]+\.(?:php) # matching file and php extension
$regex = '/^(?:[\w]\:)(?:\\[^\\:*?"<>|\r\n]+)+\\[^\\:*?"<>|\r\n]+\.(?:php)/mi';
preg_match($regex, $view_path, $matches);
return($matches[0]);
}
I've tried the pattern using https://regex101.com and it matches with the path, but it doesn't when using PHP's preg_match. Where did I make a mistake?
I haven't really looked how PHP handles string, but I tested using double backslash and correct pattern in regexonline, but php still returns null $matches
EDIT: I'm using php-5.6.17
You'd need a quadruple backslash here: inside the single quotes the double backslash is already an escaped single backslash. [Try printing the $regex
variable]
So:
$regex = '/^(?:[\w]\\:)(?:\\\\[^\\:*?"<>|\r\n]+)+\\\\[^\\\\:*?"<>|\r\n]+\\.(?:php)/mi';
Or alternatively use the here more readable nowdoc syntax:
$regex = <<<'REGEX'
/^(?:[\w]\:)(?:\\[^\\:*?"<>|\r\n]+)+\\[^\\:*?"<>|\r\n]+\.(?:php)/mi
REGEX;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments