2

I'm using php 7 and trying to remove anything after extension of urls;

Example

    https://website/sites/tag/filename/IMG25.jpg?iabc=gfds
    to 
    https://website/sites/tag/filename/IMG25.jpg

or

    https://website/sites/tag/filename/IMG25.png&iabc=gfds
    to 
    https://website/sites/tag/filename/IMG25.png

or

    https://website/sites/tag/filename/IMG25.jpeg&abc=gfds
    to 
    https://website/sites/tag/filename/IMG25.jpeg

I'm trying this function

$clean_url = preg_replace(
    "/(.+\.(:?jpg|gif|jp2|png|bmp|jpeg|svg)).*$/",
    '',
    $filename
);

But this function not working

Bynd
  • 675
  • 1
  • 15
  • 40

2 Answers2

2

I've made some adjustments to your regex in order to capture groups and replace the url by only the first group like this :

$clean_url = preg_replace(
    "/(.+(\.(jpg|gif|jp2|png|bmp|jpeg|svg)))(.*)$/",
    '${1}',
    $url
);

Sample code for all cases :

<?php

$urls = [
    "https://website/sites/tag/filename/IMG25.png&iabc=gfds",
    "https://website/sites/tag/filename/IMG25.jpg?iabc=gfds",
    "https://website/sites/tag/filename/IMG25.jpeg&abc=gfds"
];


foreach ($urls as $url){
    $clean_url = preg_replace(
        "/(.+(\.(jpg|gif|jp2|png|bmp|jpeg|svg)))(.*)$/",
        '${1}',
        $url
    );

    echo $clean_url ."\n";

}
Abdelkarim EL AMEL
  • 1,515
  • 1
  • 10
  • 10
  • my question is not to remove what after "?" the question mark; my question is how to remove what after extension example .jpg&hg=gfd – Bynd Apr 28 '19 at 10:08
  • i've noticed that you have a `&` in the second and third examples whereas in the first example you have `?`, does it have to work for both cases ? – Abdelkarim EL AMEL Apr 28 '19 at 10:15
  • I'm trying to remove anything after extension ? or & or ! ..... example I have a link like mysite/img?id=123&file=image.jpg!gh so I want to remove what is after ".jpg" – Bynd Apr 28 '19 at 10:17
  • 1
    i've updated the answer, can you have a look ? – Abdelkarim EL AMEL Apr 28 '19 at 10:32
1

You can do it this way:

First explode your url string using '?' as a delimiter, than use first element of resulted array.

explode('?', $url)[0];
Volod
  • 1,283
  • 2
  • 15
  • 34
  • 1
    your solution is good for remove after "?" but for me I want to remove anything after extension not question mark – Bynd Apr 28 '19 at 10:03
  • You are right, my bad, will try to think about another solutions – Volod Apr 28 '19 at 10:34
  • 1
    First answer now seems to be correct http://sandbox.onlinephpfunctions.com/code/9840f2a7c5ae3381f854476c5b553c5645ddc10f – Volod Apr 28 '19 at 10:37