簡體   English   中英

PHP-根據URL中最后一個目錄的名稱加載文件

[英]PHP - load a file depending on the name of the last directory in URL

如何根據URL中最后一個目錄的名稱加載PHP文件

范例1網址: http//www.example.com/en/auto/范例2網址: http//www.example.com/en/auto/mercedes/

如果url中的最后一個目錄是auto(如第一個url示例),則加載文件auto.php

如果網址中的最后一個目錄是mercedes(如第二個網址示例中所示),則加載文件mercedes.php

除了上述解決方案,您還可以嘗試以下操作:

$url = trim('http://www.example.com/en/auto', '/');
$loadUrl=substr($url, strrpos($url, '/')+1);
header("Location:".$loadUrl.".php");

正如Michael Berkowski指出的那樣, .htaccess是正確的方法,但是,您可以使用類似的東西來實現一個(非常) hack版本( 注:我不知道您打算如何“加載”文件並從哪里來,所以我在用include() ):

<?php
    // Remove trailing forward slash
    $str    =   rtrim('http://www.example.com/test/is/best/',"/");
    // Simple match characters from back
    $exp    =   preg_match("!/([a-zA-Z0-9]{1,})$!",$str,$match);
    // $match[1] gives you: best
    if(isset($match[1])) {
            // $redirect gives you: best.php
            if(is_file($redirect = $match[1].".php")) {
                    // Include the best.php
                    include($redirect);
                }
        }
?>

暫無
暫無

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

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