Created
April 13, 2016 17:56
-
-
Save comm1x/2c518b9de80c6f060b112b10f9e8d038 to your computer and use it in GitHub Desktop.
PHP function getParamsByRegex
This file contains hidden or 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 | |
/** | |
* Получает параметры из строки по регулярному выражению, например: | |
* getParamsByRegex('/<controller:\w+>/<id>/<action>', '/user/5/login') вернет массив | |
* [ | |
* 'controller' => 'user', | |
* 'id' => 5, | |
* 'action' => 'login | |
* ] | |
* @param string $pattern Регулярное выражение с параметрами вида <param> или <param:regex> | |
* При отсутствии regex, по умолчанию выбирается выражение '[^/]+' | |
* @param string $string Строка, в которой ищутся параметры | |
* @return array|bool Массив параметров, если были найдены все параметры | |
* Пустой массив, если параметры не были задани | |
* И false если один из параметров не был найден | |
*/ | |
function getParamsByRegex($pattern, $string) | |
{ | |
// Prepare pattern | |
$tr2['#'] = $tr['#'] = '\#'; | |
if (preg_match_all('/<(\w+):?(.*?)?>/', $pattern, $matches)) { | |
$tokens = array_combine($matches[1], $matches[2]); | |
foreach ($tokens as $name => $value) { | |
if ($value === '') { | |
$value = '[^/]+'; | |
} | |
$tr["<$name>"] = "(?P<$name>$value)"; | |
} | |
} else { | |
return []; | |
} | |
$p = rtrim($pattern, '*'); | |
$p = trim($p, '/'); | |
$template = preg_replace('/<(\w+):?.*?>/', '<$1>', $p); | |
$pattern = '#' . strtr($template, $tr) . '#u'; | |
// Extract values | |
preg_match($pattern, $string, $matches); | |
$params = []; | |
foreach ($tokens as $key => $regex) { | |
if (! isset($matches[$key])) { | |
return false; | |
} | |
$params[$key] = $matches[$key]; | |
} | |
return $params; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment