Php 从正则表达式中获取字符串?
有没有办法得到正则表达式的反面?简单地说,这是一个路由引擎。。。 这一切都设置得很好,但我正在编写一个函数来构建链接的URL。下面是routes.php文件:Php 从正则表达式中获取字符串?,php,regex,Php,Regex,有没有办法得到正则表达式的反面?简单地说,这是一个路由引擎。。。 这一切都设置得很好,但我正在编写一个函数来构建链接的URL。下面是routes.php文件: class Router { /* * @var urls Contains info about routes * @format '{^REGEX(?<url_paramaters>$}' => array('ControllerClassName', 'ActionName',
class Router {
/*
* @var urls Contains info about routes
* @format '{^REGEX(?<url_paramaters>$}' => array('ControllerClassName', 'ActionName', array/string('method(s)'))
*/
var $urls = array(
array('{^$}' => array('PagesController', 'index')),
array('{^contact$}' => array('PagesController', 'contact', 'get')),
array('{^about$}' => array('PagesController', 'about', 'get')),
array('{^users/(?<user_id>\d+)$}' => array('UsersController', 'show')),
);
}
对。这一切都很好。dispatcher将URL与正则表达式匹配,然后使用正则表达式后面的数组进行分派。
这是我的URL生成器函数。。。目前:
function build(array $resource = null) {
$routes = new Router;
$controller = ucwords((isset($resource['controller'])) ? $resource['controller'] : $GLOBALS['controller']) . "Controller";
$action = (isset($resource['action'])) ? $resource['action'] : 'index';
// Loop through the routes to find the right Regex using the callback
foreach($routes->urls as $route) {
$regex = array_keys($route);
$regex = $regex[0]; //Eg/ ^users/(?<user_id>\d+)$
$callback = $route[$regex];
// ?? Something in here.
}
}
假设$resource可以包含像user_id=>123这样的内容。如何将捕获组设置为正确的值?
我希望我的措辞足够好!
提前感谢,,
布拉德也许这会有所帮助
preg_match('@/users/(?P<userId>\d+)/@Uis', $_SERVER['REQUEST_URL'], $matches);
// url: /users/1/
// $matches['userId'] = 1
您应该使用普通字符串连接并准备一个普通php映射,而不是试图将正则表达式转换为普通php映射。例如:
// if $resource contains the capture groups
$keys = implode(",", array_keys($r = $resource));
// you would need an if-tree or switch to avoid notices here
$map = array(
"user_id" => "users/$r[user_id]",
"PagesController,contact,get" => "contact",
"" => "",
}
return $map[$keys];
您可以看到,正则表达式URL映射单独与捕获组是不可逆的。你需要其他关于联系方式和页面的线索。我使用了这里的路由参数作为示例。但是,您可以简单地在原始正则表达式中创建一个未使用的捕获组:
array('{^(?<contact>contact)$}' => ...
我想我明白了。这可能是一个非常糟糕的解决方案,但无论如何,它在这里。请优化它,如果你可以!助教
function build(array $resource = null) {
$routes = new Router;
$controller = ucwords((isset($resource['controller'])) ? $resource['controller'] : $GLOBALS['controller']) . "Controller";
$action = isset($resource['action']) ? $resource['action'] : 'index';
// Loop through the routes to find the right Regex using the callback
foreach($routes->urls as $route) {
$regex = array_keys($route);
$regex = $regex[0]; // ^users/(?<user_id>\d+)$
$callback = $route[$regex];
if($controller == $callback[0] && $action == $callback[1]) {
$url = substr($regex, 2, -2);
foreach($resource as $key => $value) {
$url = preg_replace("/\??\(\?<".$key.">[^\)]+\)\??/", $value, $url);
$url = preg_replace("/\)?\(?\??/", "", $url);
}
break;
}
}
return "/".$url."/";
}
这种方法并不存在。只有在最简单的情况下,才可以使用捕获组来重建原始主题—没有不特定的。*匹配,但只有像您的情况一样的固定字符串。虽然这个愿望偶尔会出现,但即使是简单的方法,也没有人编写代码。@Brad:把它作为其他偶然发现这个问题的人的答案。是的,我是新来的。我试图添加它作为评论。Doh。现在是答案了!:P