Hi, Does anyone know how to place a string into another string on a specified position ? Like this for example: $stringA = "testfile.jpg"; DO SOMETHING to insert '_new' in $stringA $stringA = "testfile_new.jpg";
If it matters for inserting it in same string that have a 3 character extension(.jpg,.exe,.bmp etc) then following might be helpful <?php $stringA="filename.jpg"; $stringB="_new"; $length=strlen($stringA); $temp1=substr($stringA,0,$length-4); $temp2=substr($stringA,$length-4,$length); echo $temp1.$stringB.$temp2; // Displays filename_new.jpg ?> Code (markup):
$string = "picture.jpg"; $new = "_new"; $pos = ".jpg"; echo str_replace($pos, $new.$pos ,$string); Code (markup):
// $insertstring - the string you want to insert // $intostring - the string you want to insert it into // $offset - the offset function str_insert($insertstring, $intostring, $offset) { $part1 = substr($intostring, 0, $offset); $part2 = substr($intostring, $offset); $part1 = $part1 . $insertstring; $whole = $part1 . $part2; return $whole; } PHP:
Problem with his function is that you always need to know how long the filename is, if he would do a reverse offset(from right to left) then you could just set offset to 4 always.
whats wrong with my solution? here as a function again: function insertstring($string, $new, $pos) { return str_replace($pos, $new.$pos ,$string); } Code (markup):
That is fine, and works like it should, and can be kept constant without adjusting the offset like in the other one.
This thread solved a big problem for me... Its really difficult to choose from which string function to use in PHP... Lots of them.
This should work no matter what the file name/extension is or how long they are: $fileName = 'filename.jpeg'; // or .gif, .jpg, etc.. $ext = '.' . end(explode('.', $fileName)); $newName = str_replace($ext, '_new' . $ext, $fileName); PHP: