我正在尝试 preg_match 一个由类别 slug、一个可选的子类别 slug 和一个选项项 slug 组成的 url。
它适用于所有情况,除了第 4 种情况。
$urls[0] = '/main_cat_slug';
$urls[1] = '/main_cat_slug/';
$urls[2] = '/main_cat_slug/sub_cat_slug';
$urls[3] = '/main_cat_slug/sub_cat_slug/';
$urls[4] = '/main_cat_slug/item.html';
$urls[5] = '/main_cat_slug/sub_cat_slug/item.html';
$regexp = array();
$regexp[] = '/(?:(?<category>[\w]+)/?)'; // Find the main category (is always available)
$regexp[] = '(?:(?<subcategory>[\w]+)/?)?'; // Find an optional sub-category, is not always available
$regexp[] = '(?:(?<item>[\w]+)\.html)?'; // Find an optional item, is not always available (don't catch the extension)
$regexp = implode('', $regexp);
foreach($urls as $index=>$url) {
preg_match("#{$regexp}#i", $url, $matches);
echo '<pre><h1>', $index, '</h1>';
echo $url, '<br />';
echo '<br />';
print_r($matches);
}
在第 4 种情况下,将找到类别,但项目为空,并且子类别获取值 op“项目”。
有人可以帮我,这样第 4 个案例只会得到一个类别和一个项目吗?
这是上面代码的输出:
0
/main_cat_slug
Array
(
[0] => /main_cat_slug
[category] => main_cat_slug
[1] => main_cat_slug
)
1
/main_cat_slug/
Array
(
[0] => /main_cat_slug/
[category] => main_cat_slug
[1] => main_cat_slug
)
2
/main_cat_slug/sub_cat_slug
Array
(
[0] => /main_cat_slug/sub_cat_slug
[category] => main_cat_slug
[1] => main_cat_slug
[subcategory] => sub_cat_slug
[2] => sub_cat_slug
)
3
/main_cat_slug/sub_cat_slug/
Array
(
[0] => /main_cat_slug/sub_cat_slug/
[category] => main_cat_slug
[1] => main_cat_slug
[subcategory] => sub_cat_slug
[2] => sub_cat_slug
)
4
/main_cat_slug/item.html
Array
(
[0] => /main_cat_slug/item
[category] => main_cat_slug
[1] => main_cat_slug
[subcategory] => item
[2] => item
)
5
/main_cat_slug/sub_cat_slug/item.html
Array
(
[0] => /main_cat_slug/sub_cat_slug/item.html
[category] => main_cat_slug
[1] => main_cat_slug
[subcategory] => sub_cat_slug
[2] => sub_cat_slug
[item] => item
[3] => item
)
亲切的问候!帕特里克