如何用数组中的一些值填充模式


How to fill a pattern with some values in an array

我有一个uri模式,我想用一些值填充它。我只有这两个变量。

$pattern = "/^(?P<scope>[a-zA-Z]+)'/(?P<node>[a-zA-Z]+)'/(?P<controller>[a-zA-Z]+)'/(?P<action>[a-zA-Z]+)$/";
$replacement = array('scope'=>'Modules', 'node'=>'Index', 'controller'=>'Index', 'action'=>'index');

我正在寻找一种输出方式:Modules/Index/Index/index

谢谢!

$output = substr($pattern, 2, -2);
$output = stripcslashes($output);
foreach ($replacement as $key => $value)
    $output = str_replace("(?P<$key>[a-zA-Z]+)", $value, $output);

这可能很有用,具体取决于您的URI,尽管它使用PHP的str_replace而不是regex。。。

$oldURI  = 'blah/<scope>/<node>/<controller>/<action>/';
$search  = array('<scope>','<node>','<controller>','<action>');
$replace = array('Modules','Index','Index','index');
$newURI  = str_replace($search, $replace, $oldURI);