Search code examples
phpregextext-extraction

Get substrings from a string containing a namespaced static method call


I am stuck with a regular expression.

$matches    = array();
// $controller = $this->getRequest()->attributes->get('_controller');
$controller = "Acme\MyBundle\Controller\MyController::myAction";
preg_match('/(.*)\\\Bundle\\\(.*)\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);

print_r($matches);

Returns (see example)

Array
(
)

Expected result

Array
(
    [0] => Acme\MyBundle\Controller\MyController::myAction
    [1] => Acme
    [2] => My
    [3] => My
    [4] => my
)

Anyone can help? This regexp seems to be legit, maybe it's just a problem with the backslashes? I tried around but didn't get it.


Solution

  • Please try below expression. Is it expected? Or tell me your exact requirements.

    <?php
    
    $matches    = array();
    // $controller = $this->getRequest()->attributes->get('_controller');
    $controller = "Acme\MyBundle\Controller\MyController::myAction";
    preg_match('/(.*)\\\(.*)Bundle\\\Controller\\\(.*)Controller::(.*)Action/', $controller, $matches);
    
    print_r($matches);