简体   繁体   中英

How to change last segment of url with php preg_replace?

I have urls like this:

/img/products/loop/blabla/81.jpg
/img/products/loop/blabla/asasd/811234.jpg
/img/productsasdasd.jpg

I want to replace this url's like this:

/img/products/loop/blabla/null.jpg
/img/products/loop/blabla/asasd/null.jpg
/img/null.jpg

How to done this ?

    $string="/img/products/loop/blabla/81.jpg";
   echo preg_replace("/[A-Za-z0-9]+[.]/","null.",$string);

Here's one way of doing it although you may also want to look at parse_url

<?php

$urls = array(
  '/img/products/loop/blabla/81.jpg',
  '/img/products/loop/blabla/asasd/811234.jpg',
  '/img/productsasdasd.jpg'
);

foreach ($urls as $url) {
  var_dump(preg_replace('#/\w+(\.\w+)$#', '/null$1', $url));
}

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