从动态URL php获取文件夹名称

时间:2015-07-03 06:19:29

标签: php url uri

我的网址可能会关注,

  

1)www.steptoinstall.com

     

2)www.steptoinstall.com/folder1

     

3)www.steptoinstall.com/folder1/index.php

     

4)www.steptoinstall.com/folder1/folder2

     

5)www.steptoinstall.com/folder1/folder2/

     

6)www.steptoinstall.com/folder1/folder2/index.php

     

7)www.steptoinstall.com/folder1/folder2/index.php?id=12

但是我想要最后一个文件夹名称,比如

1)无

2)folder1

3)folder1

4)folder2

5)folder2

6)folder2

7)folder2

我使用了以下,但没有用。

<div class="article-card">
 <%= image_tag("blog_headers/#{article.banner}")%>
</div>

如何在PHP中获取此输出,而不是在.htaccess中?

4 个答案:

答案 0 :(得分:1)

www.steptoinstall.com 
www.steptoinstall.com/folder1 folder1
www.steptoinstall.com/folder1 folder1
www.steptoinstall.com/folder1/folder2 folder2
www.steptoinstall.com/folder1/folder2 folder2
www.steptoinstall.com/folder1/folder2 folder2
www.steptoinstall.com/folder1/folder2 folder2

很抱歉,我的第一个答案是等待的,这应该是正常的。

答案 1 :(得分:0)

也许这对你有用

<?php
   $urls = array(
      'http://www.steptoinstall.com',
       'http://www.steptoinstall.com/folder1',
       'http://www.steptoinstall.com/folder1/folder2/index.php?id=12'
   );

// The Function for your work
function getFolder($url) {
    $res = parse_url($url);
    if(!isset($res['path'])) {
        return false;
    }
    $res = explode('/',$res['path']);
    $out = false;
    foreach($res as $p) {
        if(!empty($p) && strpos($p,'.')===false) $out = $p;
    }
    return $out;
}

// Testing
foreach($urls as $url) {
   var_dump(getFolder($url));

}

答案 2 :(得分:0)

如果我正确理解您的问题,您可以使用以下自定义功能

function get_arg() {
   $arguments = array();
   $path = $_SERVER['REQUEST_URI'];
   if (isset($path)) {
      $arguments = explode('/', $path);
   }
   $url_len = count($arguments);
   return ($arguments[$url_len - 2]) ? $arguments[$url_len - 2] : 'none';
 }

希望这会对你有所帮助。

答案 3 :(得分:0)

我使用正则表达式:

Get-ADGroup

输出:

<?php
$data = array(
'www.steptoinstall.com',
'www.steptoinstall.com/folder1',
'www.steptoinstall.com/folder1/index.php',
'www.steptoinstall.com/folder1/folder2',
'www.steptoinstall.com/folder1/folder2/',
'www.steptoinstall.com/folder1/folder2/index.php',
'www.steptoinstall.com/folder1/folder2/index.php?id=12',
);

foreach($data as $url)
{
    print $url." ".get_folder($url)."\n";
}

function get_folder($url)
{
    $url = preg_replace('/(.*)\/.*\..*/', '$1', $url);
    $url = preg_replace('/\/$/', '$1', $url);

    $matches = array();
    if (preg_match('/.*\/(.*)/', $url, $matches))
    {
        return $matches[1];
    }

    return '';
}

这里有一个可能的问题:很难区分“www.steptoinstall.com/folder1”和“www.steptoinstall.com/folder1/index.php” - 如果有一个没有.php结尾的SEF网址