-1

I have a string of text called doc/document1.pdf. Is there PHP code I can use that will allow me to check if the last 4 characters are equal to '.pdf'?

I am looking for code that looks like this:

<?php if($stringoftext_lastfourcharacters == '.pdf') {

echo "This is a PDF";

}

?>
Kelsey
  • 913
  • 3
  • 19
  • 41
  • http://php.net/manual-lookup.php?pattern=EN%2Fref.strings.php&lang=en&scope=404quickref – Marc B Jun 29 '15 at 20:20
  • 1
    if you want to know the file type. **Don't** use the extension use the mime type: http://php.net/manual/en/ref.fileinfo.php –  Jun 29 '15 at 20:25
  • http://php.net/manual/en/function.pathinfo.php – AbraCadaver Jun 29 '15 at 20:27
  • @AbraCadaver yeah, saw this one too http://stackoverflow.com/a/7563688/ - more than one way to hit a barn door ;-) question here could be a dupe of. – Funk Forty Niner Jun 29 '15 at 20:28

3 Answers3

9

Use substr() -

if(substr($myString, -4) == '.pdf')....

Or use pathinfo() -

$info = pathinfo($myString);
if ($info["extension"] == "pdf") .... 

You can also use explode() -

$myStringParts = explode('.', $myString);
if($myString[count($myStringParts) - 1] == 'pdf')....
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • 3
    You could wrap the substr in `strtolower()` in order to return true if the file is upper case. – Jerbot Jun 29 '15 at 20:23
3

Regex way

$reg="/\.pdf$/i";
$text= "doc/document1.pdf";
if(preg_match($reg,$text, $output_array)) { echo "This is a pdf";}
danleyb2
  • 988
  • 12
  • 18
2
if(substr($str,strlen($str)-3)==="pdf") {...}
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
wind
  • 21
  • 2