0

我有这个代码:

<?php $url = JURI::getInstance()->toString();
if ($url == "http://example.com/news/latest/"){
  echo "This is latest page";
} else {
  echo "This is not latest page";
}
?>

我要做的是代替' http://example.com/news/latest/ ',如何选择/latest/下的页面/项目。如果它更有意义,这里有一个语法:

if ($url == "http://example.com/news/latest/" + ANYTHING UNDER THIS)

我不能使用不等于 ($url !=),因为它会包含不等于 /latest/ 的其他父页面。我只想要它下面的东西。如果有人理解它,我需要有关如何将其放入代码的帮助。

更新: 我想要做的是,如果页面是 example.com/news/latest,它将回显“最新”。例如,如果我在 example.com/news/latest/subpage1/subpage2,它将回显“您在最新的页面中”。“最新”之外的任何内容都会呼应这一点。

4

2 回答 2

0
$str = 'example.com/news/latest/dfg';

preg_match('/example.com\/news\/([^\/]+)\/?(.*)/', $str, $page);

if(isset($page[2]) && $page[2])
    echo 'You are under: ' , $page[1];
elseif(isset($page[1]))
    echo 'At: ' , $page[1];
else
    echo 'Error';

编辑:澄清后切换到正则表达式。

于 2013-08-30T08:30:44.113 回答
0

使用正则表达式:

$matches = array();
if((preg_match('#http://example\.com/news/latest/(.*)#', $url, $matches)) === 1) {
    if(strlen($matches[0]) > 0) {
        echo "You're at page: $matches[0]";
    } else {
        echo "You're at the root";
    }
} else {
    // Error, incorrect URL (should not happen)
}

编辑:已修复,未经测试,因此您可能需要稍微调整一下

于 2013-08-30T08:23:16.873 回答