开发者

PHP changing part of a string

I have a php system that uploads images and suffixes their files names with -med -slider etc dependant on what size the image is. However only one of the image filenames get saved to the database, so when I want to display an image and call the filename from the database, I get something like,

filename-med.jpg how can I change th开发者_运维问答at so I can replace -med with -slider? is this possible? I am no good at regex and I assume I would have to use that?


use str_replace() like str_replace( '-med', '-slider', $file_name )


str_replace("-med", "-slider", "filename-med.jpg");


Try:

$newFilename = str_replace("-med", "-slider", "filename-med.jpg"):


It's trivial, you don't even need regex to do it. The str_replace (http://uk2.php.net/str_replace) function is what you need.

$old_filename = "foo-med.jpg"
$new_filename = str_replace('-med','-slider',$old_filename);


I would suggest just storing the "filename" part of your image, then adding on the -med.jpg, -slider.jpg ...etc at runtime.

But - if you'd rather stick with what you have, just use:

$myFile = "filename-med.jpg";
echo str_replace('-med', '-slider', $myFile);


No need for regexp, this is overkill.

I would also include ".jpg" in the haystack AND replacement strings since a filename could already contain "-med", like "test-med-med.jpg" for example.

str_replace('-med.jpg', '-slider.jpg', $filename);


Regex in this case is not overkill.

Of the str_replace() solutions presented thus far, Capsule's answer is the best, but even this one is not guaranteed to work for all possible file names. It fails in the unlikely (but very possible) case where the string '-med.jpg' is embedded inside a larger filename: e.g. filename-med.jpg_updated.jpg. It also fails if the filename has a .jpeg extension.

A 100% reliable solution is easily attained with a simple regex:

$re = '/-med\.(jpe?g|gif|png)$/mi';
$filename = preg_replace($re, '-slider.$1', $filename);

Note that this solution easily accommodates other types of image file extensions as well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜