Reputation: 483
Let's say I have a string like:
Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3
How can I get rid of _0.mp3
dynamically with PHP? The values are not hard-coded for the current example. Maybe if i use explode
?
Upvotes: 0
Views: 41
Reputation: 7074
$old = "your file name here";
$new = substr($old, 0, strrpos($old, "_"));
The substr
method will take only the part of the string that you want.
The strrpos
method finds the last index of the underscore and passes that number into the substr
method so that it knows how far to cut. This method is ideal because rather than hardcoding a specific value, the script will dynamically change for each file, just as you suggested.
Just a bit of warning: if the file name does not contain an underscore, the method won't know where to cut to and will cause error in execution. A good bit of practice would be checking if (strrpos($old, "_") !== false)
.
Upvotes: 2
Reputation: 161
Regex is your friend. Have a look at preg_match
and / or preg_replace
.
$title = preg_replace("/_[0-9]+\.mp3$/i", "", $x);
Works for blablabla_21.mp3 as well....
Upvotes: 1
Reputation: 25374
I like Confiqure's answer. To complement, you could also use a regular expression if you find that you need more power.
$old = "Cant_Hold_Us_-_Fingerstyle_Guitar_0.mp3";
$new = preg_replace('/_\d+\.mp3$/', '', $old);
Upvotes: 2