2010-08-26 109 views
1

如何從字符串結尾preg_replace .php?preg_replace「.php」?

for ($x = 0; $x < count($sidebar_links); $x++) { 

    $sidebar[$x] = $x;   
} 

$ sidebar_links:

array(3) { [0]=> string(9) "index.php" [1]=> string(9) "site2.php" [2]=> string(7) "site3.php" } 
+2

您可以使用簡單的str_replace – 2010-08-26 06:51:23

回答

4

您可以使用簡單的str_replace

李柯

str_replace('.php', '', $sidebar_links[$x]); 

basename

basename($sidebar_links[$x], ".php"); 
+0

basename是更簡單的解決方案,良好的共享。 – 2010-08-26 07:26:43

3

preg_replace('\.php$', '', $sidebar_link)

或者,以避免正則表達式:

if (substr($sidebar_link, -4) == ".php") 
    $sidebar_link = substr($sidebar_link, 0, -4); 
0

我用以下用於替換的文件擴展名的代碼。而不是隻替換未設置的最後一個數組索引。

private function changeFileExtension($imagePath, $ext=""){ 
     $arr = explode(".", $imagePath); 
     if(count($arr) > 0) 
     { 
      $arr[count($arr)-1] = $ext; 
      return implode(".", $arr); 
     } 
     else 
      return false; 
    }