繁体   English   中英

如何在网址中删除文件名的一部分

[英]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”,然后是连字符:

模式:( 演示

/\d+-gallery-/

PHP代码:( 演示

$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)) );

看到它可以帮助您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM