Search code examples
phppreg-replacepathinfo

php remove filename from url if exists


hello I would like to remove all filenames from my url :

http://website.com/folder1/folder2/filename.php

here is what I have tried :

$file_info = pathinfo('http://website.com/folder1/folder2/filename.php');
echo $file_info['dirname'];

outputs http://website.com/folder1/folder2/ wich is what I want , but when I try this :

   $file_info = pathinfo('http://website.com/folder1/folder2/');
    echo $file_info['dirname'];

it outputs http://website.com/folder1/.  
now what I want is if the url contains a filename then it gets removed , and if url has only folders then do nothing .
(I don't want to use .htaccess for this)


Solution

  • Assuming that all filenames have an extension:

    $url1 = 'http://website.com/folder1/folder2/filename.php';
    $url2 = 'http://website.com/folder1/folder2/';
    
    echo removeFilename($url1) . "\n";
    echo removeFilename($url2) . "\n";
    
    function removeFilename($url)
    {
        $file_info = pathinfo($url);
        return isset($file_info['extension'])
            ? str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url)
            : $url;
    }