@lexstile

Почему не работает регулярное выражение в одном из случаев?

Есть функция:
public function add($route, $params) {
		$route = preg_replace('/{([a-z]+):([^\}]+)}/', '(?P<\1>\2)', $route);
		$route = '#^'.$route.'$#';
		pr($route);
		$this->routes[$route] = $params;
	}
# print_r $route
    [#^text/(?P[а-яё]+)$#] => Array // 1-st example
        (
            [controller] => text
            [action] => detail
        )

    [#^text/(?P\d+)$#] => Array // 2-st example
        (
            [controller] => text
            [action] => detail
        )

Есть функция, где проверяется на рег. выр. url:
public function match() {
		$url = urldecode(trim($_SERVER['REQUEST_URI'], '/'));
		foreach ($this->routes as $route => $params) {
			if (preg_match($route, $url, $matches)) {
				foreach ($matches as $key => $match) {
					if (is_string($key)) {
						if (is_numeric($match)) {
							$match = (int) $match;
						}
						$params[$key] = $match;
					}
				}
				$this->params = $params;
				return true;
			}
		}
		return false;
	}

Файл routes:
'text/{page:[а-яё]+}' => [ // 1-st example
		'controller' => 'text',
		'action' => 'detail',
	],
	'text/{id:\d+}' => [ // 2-st example
		'controller' => 'text',
		'action' => 'detail',
	],

Вопрос в том, почему во втором примере, где {id:\d+} регулярное выражение возвращает true (например, url = text/1000), а в первом возвращает false? (например, url = text/абракадабра)
Если текущий url проверяю напрямую, все гут:
preg_match('/text\/[а-яё]+/miu', $url,$mathces) // пропадает ?P

Плюс, почему-то некорректно происходит замена - https://regex101.com/r/UdbYJ1/2
  • Вопрос задан
  • 206 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы