【问题标题】:How Do I Check If a String of Text Ends With '.PDF' Using PHP?如何使用 PHP 检查文本字符串是否以“.PDF”结尾?
【发布时间】:2015-09-16 10:56:04
【问题描述】:

我有一个名为doc/document1.pdf 的文本字符串。是否有我可以使用的 PHP 代码来检查最后 4 个字符是否等于“.pdf”?

我正在寻找如下所示的代码:

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

echo "This is a PDF";

}

?>

【问题讨论】:

标签: php string pdf


【解决方案1】:

正则表达式方式

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

【讨论】:

    【解决方案2】:

    使用substr() -

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

    或者使用pathinfo() -

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

    你也可以使用explode() -

    $myStringParts = explode('.', $myString);
    if($myString[count($myStringParts) - 1] == 'pdf')....
    

    【讨论】:

    • 您可以将 substr 包裹在 strtolower() 中,以便在文件为大写时返回 true。
    【解决方案3】:
    if(substr($str,strlen($str)-3)==="pdf") {...}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 2016-04-03
      相关资源
      最近更新 更多