Hi! Could we please enable some services and cookies to improve your experience and our website?

PHPize Online / SQLize Online  /  SQLtest Online

A A A
Login    Share code      Blog   FAQ

Online Sandbox for SQL and PHP: Write, Run, Test, and Share SQL Queries and PHP Code

Copy Format Clear

Stuck with a problem? Got Error? Ask AI support!

Copy Clear
Copy Format Clear
<?php $uri = 'uk'; $pattern = '/{context}/{alias?}'; // Извлекаем имена параметров preg_match_all('#\{([a-zA-Z0-9_]+)\??\}#', $pattern, $matches); $keys = $matches[1]; // Обрабатываем параметры в шаблоне $regex = preg_replace('#/\{([a-zA-Z0-9_]+)\?\}#', '(?:/([^/]+))?', $pattern); // Необязательные параметры $regex = preg_replace('#/\{([a-zA-Z0-9_]+)\}#', '/([^/]+)', $regex); // Обязательные параметры $regex = preg_replace('#^\{([a-zA-Z0-9_]+)\?\}#', '([^/]+)?', $regex); // Убираем ведущий `/` если параметр в начале $regex = preg_replace('#^\{([a-zA-Z0-9_]+)\}#', '([^/]+)', $regex); $regex = '#^' . $regex . '$#'; preg_match($regex, $uri, $uriMatches); // Создаём ассоциативный массив array_shift($uriMatches); // Убираем полное совпадение $uriMatches = array_combine($keys, array_pad($uriMatches, count($keys), null)); print_r($uriMatches);
Copy Clear