从字符串中删除文件扩展名

时间:2014-05-24 07:28:47

标签: php breadcrumbs

我正在创建这样的面包屑脚本:

<?php 

    if($location = substr(dirname($_SERVER['PHP_SELF']), 1)) 
         $dirlist = explode('/', $location); 
    else 
         $dirlist = array();

       $count = array_push($dirlist, basename($_SERVER['PHP_SELF'])); 
       $address = 'http://'.$_SERVER['HTTP_HOST']; 
         echo '<a href="'.$address.'">home</a>';

    for ($i = 0; $i < $count; $i++) 
         echo ' » <a href="'.($address .='/'.$dirlist[$i]).'">'.$dirlist[$i].'</a>';

?>

如果表单网址为 http:// domain /school/students.php , 结果如下:( home » school » students.php )

问题:如何消除扩展 .php 文件 students.php
像这样( home » school » students ) ??

3 个答案:

答案 0 :(得分:1)

无论扩展名或名称有多长,这都可行:

<?php
if($location = substr(dirname($_SERVER['PHP_SELF']), 1)) 
    $dirlist = explode('/', $location); 
else 
     $dirlist = array();

   $count = array_push($dirlist, basename($_SERVER['PHP_SELF'])); 
   $address = 'http://'.$_SERVER['HTTP_HOST']; 
     echo '<a href="'.$address.'">home</a>';

for ($i = 0; $i < $count; $i++) {
    $result = $dirlist[$i];
    if ($i == ($count-1)) { // if last element
        $lastDot = strripos($result,'.') ;
        $result = substr($result,0,$lastDot) ;          
    }       
    echo ' » <a href="'.($address .='/'.$dirlist[$i]).'">'.$result.'</a>';
}

&GT;

答案 1 :(得分:0)

如何使用字符串替换?

这里有一些代码可能指向正确的方向,取代你的for循环。

for ($i = 0; $i < $count; $i++) {

    $label = str_replace('.php', '', $dirlist[$i]);
    echo ' » <a href="'.($address .='/'.$dirlist[$i]).'">'.$label.'</a>';

}

答案 2 :(得分:0)

尝试扣除字符串

<?php 

if($location = substr(dirname($_SERVER['PHP_SELF']), 1)) 
     $dirlist = explode('/', $location); 
else 
     $dirlist = array();

   $count = array_push($dirlist, basename($_SERVER['PHP_SELF'])); 
   $address = 'http://'.$_SERVER['HTTP_HOST']; 
     echo '<a href="'.$address.'">home</a>';
for ($i = 0; $i < $count; $i++) 
if(!isset($dirlist[$i+1]))
{
     echo ' » <a href="'.($address .='/'.$dirlist[$i]).'">'.substr($dirlist[$i],0,-4).'</a>';
}
else
{
 echo ' » <a href="'.($address .='/'.$dirlist[$i]).'">'.$dirlist[$i].'</a>';
}

?>

这将有效。