代码之家  ›  专栏  ›  技术社区  ›  Dori

php-文本结尾的子字符串

php
  •  8
  • Dori  · 技术社区  · 16 年前

    我想从一行文本的末尾获取子字符串,比如

    $text = "bob/hello/myfile.zip";
    

    我想能够获得文件名,我想这将涉及到作为子字符串获取最后一个斜杠后的所有内容,有人能帮助我如何做到这是PHP吗?一个简单的函数

    $fileName = getFileName($text);
    
    5 回复  |  直到 13 年前
        1
  •  19
  •   Daniel Egeberg    16 年前

    退房 basename() .

        2
  •  10
  •   bschaeffer    16 年前
    $text = "bob/hello/myfile.zip";
    $file_name = end(explode("/", $text));
    echo $file_name; // myfile.zip
    

    end() 返回给定数组的最后一个元素。

        3
  •  8
  •   simplfuzz    13 年前

    对于更一般的需求,使用负值作为起始参数。
    例如

    <?php
    $str = '001234567890';
    echo substr($str,-10,4);
    ?>
    

    意志输出
    一千二百三十四

    使用一个负参数意味着它从结束的开始字符开始。

        4
  •  1
  •   Scott Saunders    16 年前

    正如Daniel发布的,对于这个应用程序,您需要使用basename()。为了更广泛的需要, strrchr() 完全按照本文标题的要求执行。

    http://us4.php.net/strrchr

        5
  •  0
  •   Curtis    16 年前

    我想您可以使用strrpos查找最后一个'/',然后只获取该子字符串:

    $filename=substr($text,strrpos($text,/')+1);

    尽管你可能真的想检查一下,确保里面有一个“/”,首先。

    推荐文章