使用php替换str中某个位置的字符

使用php替换str中某个位置的字符,php,Php,exp.要替换的字符串 150941_3D-glass-green-effect-hd-wallpapers_jpg 我需要用.jpg替换字符jpg,但是扩展名可以更改,所以我需要用点替换字符jpg。我尝试过strpos,然后substr_替换,但这会删除后面的所有内容,并包括uu 使用命令 您可以这样做: $filename = "150941_3D-glass-green-effect-hd-wallpapers_jpg"; $position = strrpos($filename,

exp.要替换的字符串

 150941_3D-glass-green-effect-hd-wallpapers_jpg 
我需要用.jpg替换字符jpg,但是扩展名可以更改,所以我需要用点替换字符jpg。我尝试过strpos,然后substr_替换,但这会删除后面的所有内容,并包括uu

使用命令

您可以这样做:

$filename = "150941_3D-glass-green-effect-hd-wallpapers_jpg";
$position = strrpos($filename, "_");
if($position !== false) {
    $filename = substr_replace($filename, ".", $position, 1);
}

使用2个扩展名进行测试,并且还支持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
检查下面的代码

$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);

你应该看一看。这将向您展示如何仅更改下划线的最后一个实例,而不影响任何其他内容。不起作用。它也替换了beginnen中的uu。此解决方案将替换字符串中的每个u。修复了代码中的错误。如果它位于字符串中的任何其他位置,它也将替换jpg。提问者还想为其他文件格式找到一个解决方案,谢谢。
$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
$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);