doudang8824
doudang8824
2015-04-18 01:42

如何检查文件中是否存在特定字符串的文件?

已采纳

I'd like to be able to search a directory for a file that starts with a specific string, for example:

- foo
  - 1_foo.jpg
  - 2_bar.png

How would I check directory foo for files that begin with "1_"?

I've tried using file_exists and preg_match like so:
if (file_exists("foo/" . preg_match("/^1_/", "foo/*"))) echo "File exists.";
but this doesn't work.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

4条回答

  • dongxiz5342 dongxiz5342 6年前

    Sounds like you need the glob() function. The glob() function searches for all the pathnames matching pattern according to the rules used by the libc glob() function, which is similar to the rules used by common shells.

    <?php
    foreach (glob('1_*.*') as $filename) {
        echo "$filename
    ";
    }
    ?>
    

    The above example will output something similar to:

    1_foo.png
    1_bar.png
    1_something.png
    
    点赞 评论 复制链接分享
  • dqce48404 dqce48404 6年前

    You can use the glob() function

    <?php
    $list = glob('1_*.*');
    var_dump($list);
    
    点赞 评论 复制链接分享
  • douchi0471 douchi0471 6年前

    Sorry, but the filesystem doesn't understand wildcards or regular expressions. To accomplish what you want, you have to open the directory and read its contents, getting a list of all the files in that directory. Then you use standard string utilities to see which filenames match your criteria.

    I think PHP's scandir is what you want as a starting point. You can also use glob but that actually forks a shell to get the file list (which in turn will do the C equivalent of scandir()).

    点赞 评论 复制链接分享
  • duanping2695 duanping2695 6年前

    I was having some trouble checking a directory and files and I gather some scripts here and there and this worked for me (Hope it helps u too):

    if ($handle = opendir('path/to/folder/')) 
    {
        while ( false !== ($entry = readdir($handle)) ) {
            if ( $entry != "." && $entry != ".." ) {
            // echo "$entry<br>";
                if (preg_match("/^filename[0-9]_[0-9].jpg/", $entry))
                {
                    // $found_it = TRUE;
                }
            }
        }
    
        closedir($handle);
    }
    
    点赞 评论 复制链接分享

为你推荐