我有以下网址路径模式
/posts(/:id:)?
用参数填充它并将它们与模式匹配的最佳方法是什么?
首先,我将相应的参数模式(:id:
)替换为提供的实际模式并构建透视输出URL
preg_replace_callback('~:([^:]+):~', function($match) {
//aggregate the match &&
//1) return the output url ||
//2) return the output pattern
}, $pattern);
根据参数,它可能与/posts/3
类似。其次,我再次调用preg_replace_callback
来构建输出模式。最后,我将两个结果preg_match
进行比较,以确保细分有效性。伪代码
argument => 3, outputUrl => /posts/3
pattern => [\d]+, outputPatterm => /posts(/[\d]+)?
preg_match(outputPattern, outputUrl) => matches...
实施例
$this->patterns = [
'id' => '[\d]+'
];
$this->arguments = [
'id' => 3
];
$pattern = '/posts(/:id:)?';
$outputPattern = preg_replace_callback('~:([^:]+):~', function($match){
return $this->patterns[$match[1]];
}, $pattern);
$outputUrl = preg_replace_callback('~:([^:]+):~', function($match){
return $this->arguments[$match[1]];
}, $pattern);
if (preg_match('~^'.$outputPattern.'$~', $outputUrl)) {
//nice, they match. Still two preg_* methods used
}