Home > php > Get file extension [PHP]

Get file extension [PHP]

Problem

You have a filename and you want to get its file extension, i.e. you want to extract the substring after the last dot.

Solution

/**
 * Return the file extension, i.e. take a string and return the
 * substring after the last dot.
 * If there is no extension, return an empty string.
 *
 * @return File extension (after the last dot) or empty string (if there is no extension).
 */
static public function get_extension($str)
{
	$ext = substr(strrchr($str, '.'), 1);
	return $ext;
}

Credits

I found this solution here. I chose this one because it’s simple enough and it returns an empty string if there is no file extension.

Advertisements
Categories: php Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: