Sanooj T
Sanooj T

Reputation: 1327

Change a string name from dotted to underscore and keep last dot

Hi i have a File name 1208.flowers.blue.jpg I want to change this name into 1208_flowers_blue.jpg

$str="1208.flowers.blue.jpg";
$count=substr_count($str,".");
if($count>1){
  //Change string to '1208_flowers_blue.jpg'
}

How will I do it ?If this question have already answered then please let me know.

Upvotes: 3

Views: 418

Answers (3)

kerala guy
kerala guy

Reputation: 21

Check this answer also as BenseidSeid in comment.

echo str_replace ('.', '_', substr ($str, 0, strrpos ($str, '.'))) . strrchr ($str, '.');

This solution fully based on string functions.

Upvotes: 1

Rohan Khude
Rohan Khude

Reputation: 4913

If you want to remove any non-word character(except a-zA-Z0-9_) then following regex will match non-word character

$str="1208.flowers.blue.jpg";
echo preg_replace("/\W(?=.*\.[^.]*$)/", "_", $str);

This will also remove the . from file name 1208.flowers.blue.jpg to 1208_flowers_blue.jpg

If you want to remove only . from filename small alteration is replace \W from regex to \.

$str="1208.flowers.blue.jpg";
echo preg_replace("/\.(?=.*\.[^.]*$)/", "_", $str);

Upvotes: 3

Indrasis Datta
Indrasis Datta

Reputation: 8606

The shortest way would be to use a REGEX:

echo preg_replace('/\.(?=.*\.)/', '_', $str);

Upvotes: 5

Related Questions