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


Removing the filename extension from a string

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

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

如果表单url是 http://domain/school/students.php
结果如下:( home » school » students.php )

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

无论扩展名或其名称有多长,这都可以工作:

<?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>';
}

?>

如何使用字符串替换?

这里有一段代码可以为你指明正确的方向,取代你的for循环。

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

尝试扣除字符串

<?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>';
}
?>