Php str_replace - two values to replace?

ぃ、小莉子 提交于 2019-12-12 01:49:41

问题


Using str_replace I want to change $url from this:

$url = http://example.com/images/lala1.jpg

to this

$url = http://example.com/images/lala1-0001.jpg

My problem is that I don't know how to insert the "-".

$url is changing so I really only know that it has ".jpg" at its' end.

My code so far:

for($i=1;$i<=9;$i++) {
    $array[] = str_replace('.jpg',sprintf("%04d",$i).'.jpg',$url); }

Any idea how I can make this work?


回答1:


Sprintf allows for regular characters in the arguments:

str_replace('.jpg', sprintf("-%04d.jpg", $i), $url);



回答2:


You might want to make use of a regular expression:

$str = preg_replace('/\.jpg$/', sprintf("-%04d.jpg",$i), $url);

This insures that it ONLY gets replaced at the end of the string.



来源:https://stackoverflow.com/questions/5862362/php-str-replace-two-values-to-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!