解析字符串 - 正则表达式或类似的东西?

sas*_*asa 2 php regex text-parsing

我正在编写路由类并需要帮助.我需要解析$ controller变量并将该字符串的一部分分配给另一个变量.以下是$ controller的示例:

$controller = "admin/package/AdminClass::display"
//$path = "admin/package";
//$class = "AdminClass";
//$method = "display";

$controller = "AdminClass::display";
//$path = "";
//$class = "AdminClass";
//$method = "display";

$controller = "display"
//$path = "";
//$class = "";
//$method = "display";
Run Code Online (Sandbox Code Playgroud)

这三种情况都是我需要的.是的,我可以编写长程序来处理这种情况,但我需要的是使用正则表达式的简单解决方案,函数preg_match_all

有什么建议怎么做?

And*_*ark 5

下面的正则表达式应该做到这一点给你,那么你可以将拍摄的组保存到$path,$class$method.

(?:(.+)/)?(?:(.+)::)?(.+)
Run Code Online (Sandbox Code Playgroud)

这是一个Rubular:http://www.rubular.com/r/1vPIhwPUub

您的PHP代码可能如下所示:

$regex = '/(?:(.+)\/)?(?:(.+)::)?(.+)/';
preg_match($regex, $controller, $matches);
$path = $matches[1];
$class = $matches[2];
$method = $matches[3];
Run Code Online (Sandbox Code Playgroud)