Reputation: 1327
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
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
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
Reputation: 8606
The shortest way would be to use a REGEX:
echo preg_replace('/\.(?=.*\.)/', '_', $str);
Upvotes: 5