简体   繁体   English

PHP正则表达式从字符串中提取控制器和动作

[英]PHP regex to extract controller and action from string

So I am developing a Symfony2 application. 因此,我正在开发一个Symfony2应用程序。 If you know what i am talking about you know how are routes structured there so I need to extract the routes and their controllers and actions. 如果您知道我在说什么,那么您会知道那里的路由结构如何,因此我需要提取路由及其控制器和操作。

I found how to extract the route object but I can't extract the controller and action, but i have the string which has them. 我找到了如何提取路线对象的方法,但是我无法提取控制器和动作,但是我有包含它们的字符串。

So I have this string: Acme\\SomeBundle\\Controller\\DefaultController::indexAction 所以我有这个字符串: Acme\\SomeBundle\\Controller\\DefaultController::indexAction

All string have similar structure. 所有字符串都具有相似的结构。 All strings end with ControllerName::ActionName. 所有字符串都以ControllerName :: ActionName结尾。 Controller name always ends with "Controller" and action name always end with "Action". 控制器名称始终以“ Controller”结尾,动作名称始终以“ Action”结尾。 So I couldnt figure how to extract theese values from the string. 所以我无法弄清楚如何从字符串中提取这些值。 I am new to regex I read about it but I don't have any clue how to do this. 我是新来的正则表达式的新手,但我不知道如何执行此操作。 Please help me, any help apreciated :) 请帮助我,任何帮助:)

Example string: 示例字符串:

`Emca\AnotherBundle\Controller\SecurityController::loginAction`

Example output: 输出示例:

SecurityController
loginAction

I think you can't do this only with one regex but two may be enough. 我认为您不能仅使用一个正则表达式来做到这一点,但两个就足够了。 Thank you! 谢谢!

An example can be found in symfony's ControllerNameParser class: 在symfony的ControllerNameParser类中可以找到一个示例:

$controller = 'Acme\YourBundle\Controller\SecurityController::loginAction';

if (0 === preg_match('#^(.*?\\\\Controller\\\\(.+)Controller)::(.+)Action$#', $controller, $match)) {
    throw new \InvalidArgumentException(sprintf('The "%s" controller is not a valid "class::method" string.', $controller));
}

$className      = $match[1];
$controllerName = $match[2];
$actionName     = $match[3];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM