简体   繁体   中英

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

I need to remove a substring from the start of filename urls.

The substring that I need to remove is always a series of numbers then a hyphen then the word gallery then another hyphen.

eg 2207-gallery- , 2208-gallery- , 1245-gallery- , etc.

How can I change this:

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

to this:

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

The substring to be replaced is always different.

This will match 1 or more digits then hyphen then "gallery" then hyphen:

Pattern: ( Demo )

/\d+-gallery-/

PHP Code: ( 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);

Output:

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

Here is your non-regex method:

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

on PHP do this :

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

See it help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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