0

While this works perfectly, looking for a way to make it a little / lot cleaner, and also to learn along the way!!! I am adding /thumbs to a directory and file string, and also adding _thumb to the end of the file name of that same string.

from this... Gallery/Test/Image/image.jpg

to this... Gallery/Test/Image/thumbs/image_thumb.jpg

but the paths can change in length depending on the directory structure, but /thumbs will always be the last directory, and _thumb will always be before the "."

    $thumb_dir = substr($file, 0, strrpos($file, '/')) . '/thumbs' . substr($file, strrpos($file, '/'));

    $thumbnail = substr($thumb_dir, 0, strrpos($thumb_dir, '.')) . '_thumb' . substr($thumb_dir, strrpos($thumb_dir, '.'));

Thanks

1
  • You can also do it with Regular Expressions: 3v4l.org/AjNgC I'm not posting it as an answer because the accepted answer is definitely a better solution. But I thought it was an interesting approach. Commented Jul 24, 2017 at 2:27

1 Answer 1

3

pathinfo might help you if your PHP version is > 5.2.0+

$path_parts = pathinfo('Gallery/Test/Image/image.jpg');
echo $path_parts['dirname'].'/thumbs/'.$path_parts['filename'].'_thumb.'.$path_parts['extension'];

Little explanation of the code

$path_parts['dirname'] would fetch the complete directory path of the path given in this case it would be Gallery/Test/Image. Then we added a directory called '/thumbs/' into the string. next we should get the name of the file using $path_parts['filename'] which would fetch image and not image.jpg and furthur we added '_thumb.' to it. and later we suffix with the extension.

Sign up to request clarification or add additional context in comments.

3 Comments

I'm on 5.31, so I will give it a try, much appreciated!
Hey Mohit, That worked perfectly, thank you!! Also thanks for the explanation, I also read the function documentation! Really appreciate your help!
Hey @Simon. Thanks for the kind words. Happy to help. :)

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.