Reputation: 1129
I am retrieving file locations and names from a database, the are in this format
http://domain.com/subdir/etc/etc/etc/picimage-niceone_Main-150x150.jpg
They are all dynamic, so there are hundreds of them all with different names, but one thing is constant is the last - and then the file dimensions.
What i need to do is strip everything after the last - so it turns into the following.
http://domain.com/subdir/etc/etc/etc/picimage-niceone_Main.jpg
Any help would be awesome.
Cheers,
Upvotes: 0
Views: 111
Reputation: 339816
Look at preg_replace()
:
$url = preg_replace('/\-(\d+)x(\d+)(\.\w+)$/', '$3', $url);
i.e. find a hyphen, a number, an 'x', a number, and an extension, and replace the whole thing with just the extension.
Alternatively, if you actually want to know what those width and height values were (for example to populate <IMG>
tag attributes:
$url = 'http://domain.com/subdir/etc/etc/etc/picimage-niceone_Main-150x150.jpg';
$regex = '/(.*?)-(\d+)x(\d+)(\.\w+)$/';
if (preg_match($regex, $url, $matches)) {
$width = $matches[2];
$height = $matches[3];
$url = $matches[1] . $matches[4];
}
Upvotes: 1
Reputation: 21082
$stringName = "picimage-niceone_Main-150x150.jpg";
$newName = substr($stringName,0,strrpos($stringName,"-")).substr($stringName,-4);
This will remove anything between the last -
and the file extension.
Upvotes: 1
Reputation: 169018
$newname = preg_replace("/-[^-.]*(\\.[a-zA-Z]*)$/", '$1', $oldname);
Upvotes: 0