Search code examples
phppreg-matchico

How to use preg_match with file extension in PHP 5.6


I'm looking for a file which name is like this string: .047b2edb.ico

I am not sure how to add "ico" extension to my preg_match function.

[.a-zA-Z0-9]

Any suggestions would be appreciated

This is my whole code. With this code I can't find a file with name .62045303.ico where is the problem ?

<?php
$filepath = recursiveScan('/public_html/');

function recursiveScan($dir) {
    $tree = glob(rtrim($dir, '/') . '/*');
    if (is_array($tree)) {
        foreach($tree as $file) {
            if (is_dir($file)) {
                //echo $file . '<br/>';
                recursiveScan($file);
            } elseif (is_file($file)) {
               if (preg_match_all("(/[.a-zA-Z0-9]+\.ico/)", $file )) {
                   //echo $file . '<br/>';
                   unlink($file);
               }

            }
        }
    }
}
?>

Solution

  • [.a-zA-Z0-9]+\.ico
    

    will do it.

    Explanation:

    [.a-zA-Z0-9]  match a character which is a dot, a-z, A-Z or 0-9
    +             match one or more of these characters
    \.ico         match literally dot followed by "ico".
                  the backslash is needed to escape the dot as it is a metacharacter
    

    Example:

    $string = 'the filenames are .asdf.ico and fdsa.ico';
    
    preg_match_all('/[.a-zA-Z0-9]+\.ico/', $string, $matches);
    
    print_r($matches);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => .asdf.ico
                [1] => fdsa.ico
            )
    
    )