Created
April 16, 2017 02:11
-
-
Save kamermans/0fb40ea7135ef48b6acb739695e39cd7 to your computer and use it in GitHub Desktop.
PHP port of the Python 2.7 `fnmatch::translate()` function to convert shell-expansion patterns to regular expressions.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Direct port of the Python 2.7 fnmatch::translate(pat) function. | |
* Converts a shell-expansion pattern to a regular expression. | |
* | |
* by Steve Kamerman | |
* | |
* @see https://hg.python.org/cpython/file/2.7/Lib/fnmatch.py | |
*/ | |
function pythonFnmatchTranslate($pat, $delimiter=null) { | |
$i = 0; | |
$n = strlen($pat); | |
$res = ''; | |
while ($i < $n) { | |
$c = $pat[$i]; | |
$i++; | |
if ($c === '*') { | |
$res .= '.*'; | |
} else if ($c === '?') { | |
$res .= '.'; | |
} else if ($c === '[') { | |
$j = $i; | |
if ($j < $n && $pat[$j] === '!') { | |
$j++; | |
} | |
if ($j < $n && $pat[$j] === ']') { | |
$j++; | |
} | |
while ($j < $n && $pat[$j] !== ']') { | |
$j++; | |
} | |
if ($j >= $n) { | |
$res .= '\\['; | |
} else { | |
$stuff = substr($pat, $i, ($j - $i)); | |
$stuff = str_replace('\\','\\\\', $stuff); | |
$i = $j + 1; | |
if ($stuff[0] === '!') { | |
$stuff = '^' . substr($stuff, 1); | |
} else if ($stuff[0] === '^') { | |
$stuff = '\\' . $stuff; | |
} | |
$res = sprintf('%s[%s]', $res, $stuff); | |
} | |
} else { | |
$res .= preg_quote($c); | |
} | |
} | |
$res = '^(?ms)' . $res . '$'; | |
// Unlike in Python, PHP requires delimiters. | |
if ($delimiter !== null) { | |
$res = str_replace($delimiter, '\\'.$delimiter, $res); | |
$res = $delimiter . $res . $delimiter; | |
} | |
return $res; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment