String manipulation simple. |
[eluser]solid9[/eluser]
Okay I have a filename string below, Code: smile.jpg Now I wanted to insert the word '_thumb' to make it look like this below, Code: smile_thumb.jpg What string functions should I used to accomplish this? Thanks in advanced.
[eluser]Nisha S.[/eluser]
You can use preg_replace function. If you have only the jpg extension for the files, then you can also replace ".jpg" with "_thumb.jpg". http://php.net/manual/en/function.preg-replace.php
[eluser]boltsabre[/eluser]
try to stay away from preg-replace and preg-match as much as you can, it's quiet intensive in regards to the resources it uses. For this is should be okay, but as a general rule of thumb, if you can get away without using it, it's better. For this, I'd actually just put "thumb_" at the start of the file name Code: $name = smile.jpg; Then if you need the filename without "thumb_", you just strip away the first 6 characters, and you have the original again. It's harder to strip thumb from the end... you can do it by counting backwards and ignoring .jpg, but what if the extension (for whatever reason) is .jpeg, now your count if off by one. Or what happens if you used a string replace function to replace "_thumb" with "" and the file name already had "_thumb" in it? Code: $name = 'user_photoname_thumb_123.jpg'; What are the chances of having the extension .jpeg or a filename already having "_thumb" in it...??? If you're dealing just with your own files, well that depends on how careful you are! (But wait... what if you're working on it 3 years later, will you still remember to check for these 2 things? Or are you a team of developers, will everyone remember all the time?). Or if the file is coming from user input, it could happen often (but in which case you'd want to be scrambling the filename anyway, but even after that, it could be theoretically possible to end up with a scrambled name with "_thumb" in depending on your scrambling mechanism. You could do lots of extra coding to prevent the above from happening... but why bother? Just add "thumb_" at the start, and it's SOOOO easy to strip back off to get the original name! Anyway, the whole point of this post is just to point out that you have to consider what possible pitfalls your approach may have. Keep it KISS (keep it simple silly) (no offence meant with the "silly") and you've prevent yourself lots of bugs, grey hairs from trying to debug them and websites that crash (or don't load the full image because you end up with the incorrect file name!)
[eluser]CroNiX[/eluser]
This should work even if the filename has multiple dots, regardless of the file extension. Code: function append_to_filename($file, $append_text = '_thumb') //Default of _thumb Code: $file = 'my.image.file.jpg';
|
Welcome Guest, Not a member yet? Register Sign In |