3

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?

4 Answers 4

6

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
Sign up to request clarification or add additional context in comments.

4 Comments

This would fail if for some reason the file name had an extra dot in it like: recent.image.jpg. The result would be recent_hu.image.jpg
Sorry you must have caught me in between updates. Updated to work properly now.
this will fail if the filename has $ext inside of the name: 'image.gift.1234.gif'
@stevecomrie, Try this, fast and can correct to show it, stackoverflow.com/a/75505259/5049864
5

Using preg_replace would work well:

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

7 Comments

Note - this code will only work for JPGs. For a more universal method, try explode().
@Duthcie432: Or you could just change the regexp from '/\.jpg$/' to '/\.[a-z0-9]+$/' and it will work for all file extensions.
Fair enough. What if the filename has more than one . like image.test.png
I determine the filename and the extension, so the first example works for me. I edited the question: $lang is without the '_' character. I modified the first example, that is working, but what I need to modify, when I want to use the more universal version '/\.jpg$/' to '/\.[a-z0-9]+$/'
@Galen - again this only works for files with one .. So in that respect it works just as well as accepted answer
|
3

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'];

1 Comment

I think this is actually a much more readable solution than any of the regex ones based ones.
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.