Php, удалить из строчки все лишнее

/upl/img/2jf-img1.webp?id=2335

Как удалить из строчки все и оставить только img1.webp

То есть "2jf-" может не быть, а может и есть равно как из все то что за знаком "?"


Ответы (3 шт):

Автор решения: Apo-S
preg_replace('~(?:.*-)?([^/]+?)(?:\?.*)?$~', '$1', $str);

Результаты:

/upl/img/2jf-img1.webp?id=2335 -> img1.webp
/upl/img/user/2/2jf-img1.webp?id=2335 -> img1.webp
/upl/assets/img1.webp?id=2335 -> img1.webp
/im1.jpg -> im1.jpg
/im1.jpg? -> im1.jpg
/im1.jpg?id=xxx -> im1.jpg
/xyz-im1.jpg?id=xxx -> im1.jpg
-im1.jpg?id=xxx -> im1.jpg
→ Ссылка
Автор решения: sdasadf

Если 2jf- может не быть, но обязательное, если есть, то

$name = basename(parse_url('/upl/img/2jf-img1.webp?id=2335')['path']);
echo $name;
→ Ссылка
Автор решения: vp_arth

Можно просто порезать explode:

function foo($src) {
    $res = explode('?', $src)[0];
    $res = explode('/', $res);
    $res = array_pop($res);
    $res = explode('-', $res);
    $res = array_pop($res);
    return $res;    
}


echo foo('/upl/img/2jf-img1.webp?id=2335'), PHP_EOL;
echo foo('/upl/img/img1.webp?id=2335'), PHP_EOL;
echo foo('/upl/img/2jf-img1.webp'), PHP_EOL;
echo foo('/a/b/c/d/e/f/g/h/i/img1.webp'), PHP_EOL;

Можно регуляным выражением:

function foo($src) {
    preg_match('#([^-/\?]+)(?:\?.*|$)#', $src, $m);
    return $m ? $m[1] : '';
}

parse_url:

function foo($src) {
    $res = basename(parse_url($src)['path']);
    $res = explode('-', $res);
    $res = array_pop($res);
    return $res;    
}

3v4l

→ Ссылка