如何在 url 中删除部分文件名

How to remove part of a file's name in a url

我需要从文件名 url 的开头删除一个子字符串。

我需要删除的子字符串始终是一系列数字,然后是连字符,然后是单词 gallery,然后是另一个连字符。

例如2207-gallery- , 2208-gallery- , 1245-gallery-

我该如何更改:

http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg

对此:

http://img.pass.com:7710/img.pass.com/img-1/25171-content_gallery-1428380843.jpg

要替换的子字符串总是不同的。

这将匹配 1 个或多个数字,然后是连字符,然后是 "gallery",然后是连字符:

模式:(Demo)

/\d+-gallery-/

PHP代码:(Demo)

$image='http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg';
echo preg_replace('/\d+-gallery-/','',$image);

输出:

http://img.pass.com:7710/img.pass.com/img-1/25171-content_gallery-1428380843.jpg

这是您的非正则表达式方法:

echo substr($image,0,strrpos($image,'/')+1),substr($image,strpos($image,'-gallery-')+9);

PHP 上执行此操作:

function renameURL($originalUrl){
    $array1 = explode("/", $originalUrl);
    $lastPart = $array1[count($array1)-1];//Get only the name of the image
    $array2 = explode("-", $lastPart);
    $newLastPart = implode("-", array_slice($array2, 2));//Delete the first two parts (2207 & gallery)
    $array1[count($array1)-1] = $newLastPart;//Concatenate the url and the image name
    return implode("/", $array1);//return the new url
}
//Using the function : 
$url = renameURL($url);

DEMO

function get_numerics ($str) {
    preg_match_all('/\d+/', $str, $matches);
    return $matches[0];
}

$one = 'http://img.pass.com:7710/img.pass.com/img-1/2207-gallery-25171-content_gallery-1428380843.jpg';


$pos1 = strpos($one, get_numerics($one)[3]);
$pos2 = strrpos($one, '/')+1;
echo ( (substr($one, 0, $pos2).substr($one, $pos1)) );

看到它对你有帮助。