The Right Way to Get a File Extension in PHP

I made a recent search on retrieving file extensions in PHP.

I found out that a lot have been re-inventing the wheel. They have been creating code for functionality that PHP already has. This is one example of re-inventing the wheel

function get_file_extension($file_name)
{
return substr(strrchr($file_name,’.’),1);
}

Another example was this:

function file_extension($filename)
{
return end(explode(“.”, $filename));
}

PHP already has a function that does the same thing and more.

Welcome, pathinfo.

$file_path = pathinfo(‘/www/htdocs/your_image.jpg’);
echo “$file_path [‘dirname’]\n”;
echo “$file_path [‘basename’]\n”;
echo “$file_path [‘extension’]\n”;
echo “$file_path [‘filename’]\n”; // only in PHP 5.2+


// Output
/www/htdocs
your_image.jpg
jpg
your_image

A much easier way to use the constants:
[PATHINFO_DIRNAME | PATHINFO_BASENAME | PATHINFO_EXTENSION | PATHINFO_FILENAME]

PATHINFO_DIRNAME – the directory
PATHINFO_BASENAME – the file name
PATHINFO_EXTENSION – the extension
PATHINFO_FILENAME – the filename without the extension

echo pathinfo(‘/www/htdocs/your_image.jpg’, PATHINFO_EXTENSION);

// Output

jpg

How to count how many times a certain word is used ,using php?

01 <?php
02 $count = 0; // count start form zero
03 $string = "bugphp -free online tutorials bugphp.com bugphp bugphp.com bugphpbugphp bugphp";
04
05 foreach( str_word_count($string ,1) as $a ) {
06 if( strtolower($a) == strtolower('bugphp') )  {
07 $count++;
08 }
09 }
10 echo "$count";
11 ?>