简体   繁体   中英

How Do I Check If a String of Text Ends With '.PDF' Using PHP?

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";

}

?>

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')....

Regex way

$reg="/\.pdf$/i";
$text= "doc/document1.pdf";
if(preg_match($reg,$text, $output_array)) { echo "This is a pdf";}
if(substr($str,strlen($str)-3)==="pdf") {...}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM