问题
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