$re = '`^(?:/api|/apis/(?P<GROUP>[^/]+))/(?P<VERSION>[^/]+)(?:/namespaces/(?P<NAMESPACE>[^/]+))?/(?P<RESOURCETYPE>[^/\n]+)(?:/(?P<NAME>[^/\n]+))?(?:/(?P<SUBRESOURCE>[^/\n]+))?$`m';
$str = '## Cluster-scoped resources
/api/v1/RESOURCETYPE
/api/v1/RESOURCETYPE/NAME
/apis/GROUP/VERSION/RESOURCETYPE
/apis/GROUP/VERSION/RESOURCETYPE/NAME
## Namespace-scoped resources:
/api/v1/namespaces/NAMESPACE/RESOURCETYPE
/api/v1/namespaces/NAMESPACE/RESOURCETYPE/NAME
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE/NAME
## Cluster-scoped subresource:
/api/v1/RESOURCETYPE/NAME/SUBRESOURCE
/apis/GROUP/VERSION/RESOURCETYPE/NAME/SUBRESOURCE
## Namespace-scoped subresource
/api/v1/namespaces/NAMESPACE/RESOURCETYPE/NAME/SUBRESOURCE
/apis/GROUP/VERSION/namespaces/NAMESPACE/RESOURCETYPE/NAME/SUBRESOURCE';
preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
// Print the entire match result
var_dump($matches);
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for PHP, please visit: http://php.net/manual/en/ref.pcre.php