Search code examples
phpregexsubstringpreg-replacefilenames

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.

e.g. 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.


Solution

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