-1

exp. string to replace;

 150941_3D-glass-green-effect-hd-wallpapers_jpg 

I need to replace the character _jpg with .jpg but the extension can change so I need _ to be replaced with a point. I have tried strpos and then substr_replace but this removes everything after and include the _.

ajacian81
  • 7,419
  • 9
  • 51
  • 64
phpFreak
  • 133
  • 1
  • 1
  • 8
  • You should take a look at [PHP Replace Last Occurence of a String in a String?](http://stackoverflow.com/questions/3835636/php-replace-last-occurence-of-a-string-in-a-string). This will show you how to change only the last instance of the underscore without affecting anything else. – SnoringFrog Sep 09 '14 at 13:27

5 Answers5

2

Tested with 2 extensions and also accounts for jpeg

$str1 = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$str2 = '150941_3D-glass-green-effect-hd-wallpapers_png';

$str1 = preg_replace('/_([a-z]{3,4})$/', '.$1', $str1);
$str2 = preg_replace('/_([a-z]{3,4})$/', '.$1', $str2);

echo $str1; //150941_3D-glass-green-effect-hd-wallpapers.jpg
echo $str2; //150941_3D-glass-green-effect-hd-wallpapers.png
Onimusha
  • 3,348
  • 2
  • 26
  • 32
1

Use the str_replace command.

$string = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$new = '.jpg' // or wathever you want.
$new_string = str_replace('_jpg', $new, $string);
Wezy
  • 665
  • 1
  • 5
  • 14
  • This will also replace _jpg if it's anywhere else in string. And also questioner wanted a solution for other file formats too – Onimusha Sep 09 '14 at 13:33
1

You could do this:

$filename = "150941_3D-glass-green-effect-hd-wallpapers_jpg";
$position = strrpos($filename, "_");
if($position !== false) {
    $filename = substr_replace($filename, ".", $position, 1);
}
Jeroen de Jong
  • 337
  • 1
  • 6
0
<?php
$o = "150941_3D-glass-green-effect-hd-wallpapers_jpg";
$o = preg_replace("/_([^_]+)$/", ".\\1", $o);
echo $o;
jancha
  • 4,916
  • 1
  • 24
  • 39
0

Check below code

$imgExt = array('_jpg','_jpeg','_png','_bmp','_gif');
$replaceExt = array('.jpg','.jpeg','.png','.bmp','.gif');
$string = '150941_3D-glass-green-effect-hd-wallpapers_jpg';
$replacedText = str_replace($imgExt,$replaceExt,$string);
Mahadeva Prasad
  • 709
  • 8
  • 19