如何通过php删除日期str_replace

问题描述 投票:0回答:1

我正在学习php语言。我想显示如下输出。只需删除这些地址中的日期即可。我不知道如何添加代码和删除它。

/2018/10/10/
/2019/11/13/
/2020/12/15/

我的网址:

https://1.1.1.1/2018/10/10/filename-picture-01.jpg   -> out: filename-picture-01.jpg
https://1.1.1.1/2019/11/13/filename-picture-02.jpeg  -> out: filename-picture-02.jpg
https://1.1.1.1/2020/12/15/filename-picture-03.png   -> out: filename-picture-03.jpg
https://1.1.1.1/2020/12/18/filename-picture-03.bmp   -> out: filename-picture-03.jpg

我的PHP

$out = str_replace( array('.png','.jpeg','.bmp','.gif') , '.jpg' , $url);  /// Remove file ext
$out = str_replace( 'https://1.1.1.1/' , '' , $url); /// Remove url
echo $out;
php url replace
1个回答
0
投票

您可以使用 PHP 的内置函数,如 parse-urlbasename 来实现此目的。

我创建了一个名为

getFileNameFromUrl
的函数,并添加了代码的简短说明作为注释。

<?php

function getFileNameFromUrl($url) {
    // Use parse_url to extract the path from the URL
    $path = parse_url($url, PHP_URL_PATH);

    // Use basename to get the file name from the path
    $fileName = basename($path);

    return $fileName;
}


// Example usage:
$url1 = 'https://1.1.1.1/2018/10/10/filename-picture-01.jpg';
$url2 = 'https://1.1.1.1/2018/10/10/filename-picture-02.jpg';

$fileName1 = getFileNameFromUrl($url1);
$fileName2 = getFileNameFromUrl($url2);

echo "File Name 1: $fileName1"; // output: filename-picture-01.jpg
echo "File Name 2: $fileName2"; // output: filename-picture-02.jpg
© www.soinside.com 2019 - 2024. All rights reserved.