views:

45

answers:

3

Hi. How do I preg_replace .php from end of string?

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" } 
+3  A: 

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

Or, to avoid regex:

if (substr($sidebar_link, -4) == ".php")
     $sidebar_link = substr($sidebar_link, 0, -4);
Gabi Purcaru
+4  A: 

you can use simple str_replace

like

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

or basename

basename($sidebar_links[$x], ".php");
Haim Evgi
basename is the easier solution, good sharing.
Ayaz Alavi
+1  A: 

I used following code for replacing file extension. Instead of replacing just unset last index of array.

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