簡體   English   中英

PHP-將代碼應用於子頁面

[英]PHP - Apply code to subpages

我有以下代碼:

<?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中,它將回顯“您所在的頁面位於“最新”頁面下”。 除“最新”之外的任何內容都將得到回應。

使用正則表達式:

$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)
}

編輯:固定,未經測試,所以您可能需要調整一下

$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';

編輯:澄清后切換為正則表達式。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM