phpregexfilenamestext-parsing

Get filename without its extension from a filepath string


How can I catch and sanitize the below filename?

Input:

../images/imgac00000001.jpg
../images/imgbc00000002.jpg
../images/img1111.jpg

Output:

imgac00000001
imgbc00000002
img1111

I have tried in PHP using preg_replace(), which I don't know how to use correctly.

preg_replace('/(img)[a-z]{0,2}[0-9]*/i', '$1', $img_path);

Solution

  • You need to use preg_match_all, not preg_replace

    $input = <<<EOF
    ../images/imgac00000001.jpg
    ../images/imgbc00000002.jpg
    ../images/img1111.jpg
    EOF;
    
    //imgac00000001
    //imgbc00000002
    
    
    preg_match_all('/img[a-z]{0,2}[0-9]*/i', $input, $matches);
    
    print_r($matches);
    

    Output:

    Array
    (
        [0] => Array
            (
                [0] => imgac00000001
                [1] => imgbc00000002
                [2] => img1111
            )
    
    )