开发者

php, add string to filename

开发者 https://www.devze.com 2023-03-03 03:39 出处:网络
I have two variable: $lang = hu $image = image.jpg How to replace image.jp开发者_如何学运维g to image_hu.jpg in php? Maybe with str_replace? But how? this method will work for any file type and wi

I have two variable:

$lang = hu

$image = image.jpg

How to replace image.jp开发者_如何学运维g to image_hu.jpg in php? Maybe with str_replace? But how?


this method will work for any file type and with image names that have more than one period. (DEMO)

Code

<?php 

    echo merge('image.test.1234.gif', '_en');

    function merge($file, $language){
        $ext = pathinfo($file, PATHINFO_EXTENSION);
        $filename = str_replace('.'.$ext, '', $file).$language.'.'.$ext;
        return ($filename);
    }
?>

Result

image.test.1234_en.gif


Using preg_replace would work well:

$new_str = preg_replace('/(\.[^.]+)$/', sprintf('%s$1', $lang), $image);


Another option would be to use the built in function pathinfo to separate the file extension from the filename.

$path_parts = pathinfo('image.jpg');

$final = $path_parts['filename'] . $lang . '.' . $path_parts['extension'];


I would use the following:

$new_str = preg_replace( '/^(.*?)\.(\w+)$/', '${1}$lang.${2}', $image );

That way your code would still work for JPG/gif/jpeg/PNG/etc

0

精彩评论

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