How to remove path after domain name from string

I have the following code:

function removeFilename($url)
{
    $file_info = pathinfo($url);
    return isset($file_info['extension'])
        ? str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url)
        : $url;
}

$url1 = "http://website.com/folder/filename.php";
$url2 = "http://website.com/folder/";
$url3 = "http://website.com/";
echo removeFilename($url1); //outputs http://website.com/folder/
echo removeFilename($url2);//outputs http://website.com/folder/
echo removeFilename($url3);//outputs http:///

      

Now my problem is when there is only a domain with no folders or filenames, my function deletes the site as well.

My idea is that in PHP there is some way to tell that my function only does work after the third slash or any other solutions you find useful.

+3


source to share


5 answers


UPDATED: (works and tested)

<?php
function removeFilename($url)
{
        $parse_file = parse_url($url);
        $file_info = pathinfo($parse_file['path']);
        return isset($file_info['extension'])
            ?  str_replace($file_info['filename'] . "." . $file_info['extension'], "", $url)
            :  $url;        
}

$url1 = "http://website.com/folder/filename.com";
$url2 = "http://website.org/folder/";
$url3 = "http://website.com/";

echo removeFilename($url1); echo '<br/>';
echo removeFilename($url2); echo '<br/>';
echo removeFilename($url3);
?>

      



Output:

http://website.com/folder/
http://website.org/folder/
http://website.com/

      

+2


source


It sounds like you want to replace the substring, not everything. This function can help you:



http://php.net/manual/en/function.substr-replace.php

0


source


pathinfo can not only recognize the domain and file name. But if without the filename url ends with a slash

$a = array(
"http://website.com/folder/filename.php",
"http://website.com/folder/",
"http://website.com",
);

foreach ($a as $item) {
   $item = explode('/', $item);
   if (count($item) > 3)
      $item[count($item)-1] ='';;
   echo implode('/', $item) . "\n";

}
  result

http://website.com/folder/
http://website.com/folder/
http://website.com

      

0


source


Because the file name is the last slash, you can use substr

and str_replace

to remove the file name from the path.

$PATH = "http://website.com/folder/filename.php";

$file = substr( strrchr( $PATH, "/" ), 1) ; 
echo $dir = str_replace( $file, '', $PATH ) ;

      

OUTPUT

http://website.com/folder/

0


source


Close to answer by splash58

function getPath($url) {
    $item = explode('/', $url);
    if (count($item) > 3) {
        if (strpos($item[count($item) - 1], ".") === false) {
            return $url;
        }
        $item[count($item)-1] ='';
        return implode('/', $item);
    }
    return $url;
}

      

0


source







All Articles