Dec
2
Regular Expression to match a Windows (Local and UNC) or UNIX Path
Sam Burney | Tue, 12/02/2008 - 11:23
I've been looking for a regular expression (regex) to get a path, file name and extension from a full UNIX path for a small app I'm working on but could only come across Windows ones.
For anyone looking, here I've come up with what I was looking for: A regular expression to match a Windows (Both UNC and Local paths) or UNIX paths as well as breaking that path into it's relavant segments all in one go.
Regular Expression:
^(.*?/|.*?\\)?([^\./|^\.\\]+)(?:\.([^\\]*)|)$
PHP Function Example:
// Split filepath path, name and extension
function namesplit($path)
{
preg_match('@^(.*?/|.*?\\\\)?([^\./|^\.\\\\]+)(?:\.([^\\\\]*)|)$@', $path, $namesplit);
return $namesplit;
}
Output Example:
Array ( [0] => /path/to/file/filename.ext [1] => /path/to/file/ [2] => filename [3] => ext )
I hope this saves someone some time!
Tags: