duandong9195 2015-11-02 18:44
浏览 94
已采纳

PHP URL数组返回先前路由数组的结果

I use URL routing on my website and this is the code I use:

/* TURN FULL URL INTO --> /example/example2/example3 */
function getCurrentUri()
{
    $basepath = implode('/', array_slice(explode('/', $_SERVER['SCRIPT_NAME']), 0, -1)) . '/';
    $uri = substr($_SERVER['REQUEST_URI'], strlen($basepath));
    if (strstr($uri, '?')) $uri = substr($uri, 0, strpos($uri, '?'));
    $uri = '/' . trim($uri, '/');
    return $uri;
}
$base_url = getCurrentUri();
$routes = array();
$routes = explode('/', $base_url);
foreach($routes as $route)
{
    if(trim($route) != ''){
        array_push($routes, $route);
    }
}

For some reason it outputs the following when using var_dump() on $routes[0], $routes[1], $routes[2] and $routes[3]. This is while being on the following website: http://localhost/tutorials/

string '' (length=0)
string 'tutorials' (length=9)
string 'tutorials' (length=9)
null

How can I solve this routing problem?

  • 写回答

1条回答 默认 最新

  • dongzi8191 2015-11-02 18:59
    关注

    If I understand it correctly:

    1. You created array variable $routes.
    2. Then you fill that array with strings from explode('/', $base_url).
    3. You iterate that array and if string is not '', then you push that string onto the end of array.

    To avoid this, you can use array_pop() instead of array_push() and change condition from trim($route) != '' to trim($route) === '' || trim($route) === null. Second condition is needed to remove null element from array.

    Or you can assign explode('/', $base_url) to different variable, e.g. $explodedUrls and iterave over its.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!