I have two variable:
$lang = hu
$image = image.jpg
How to replace image.jpg 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
recent.image.jpg. The result would be recent_hu.image.jpg'image.gift.1234.gif'Using preg_replace would work well:
$new_str = preg_replace('/(\.[^.]+)$/', sprintf('%s$1', $lang), $image);
explode().. like image.test.png.. So in that respect it works just as well as accepted answerAnother 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'];