Search code examples
phpregexpathfilenamestext-parsing

Get the filename from a filepath string


Please help finding the correct pattern of the following case

simple strings are:

pdf/20120102/A1_standard.pdf
pdf/20130431/1.pdf
pdf/20110506/abcde.pdf
pdf/20131201/fff-01/02/12/-A1.pdf

The substring I need to match is A1_standard.pdf , 1.pdf, abcde.pdf , fff-01/02/12/-A1.pdf

I have tried ///*.pdf/ as the pattern but it seems not working. The case 4 is more difficult as there is a '/' in the filename, if it can not be solved right now, just ingore this case.


Solution

  • Try this :

    $str  = 'pdf/20120102/A1_standard.pdf';
    preg_match('/(?P<file>[\w\-]+\.pdf)$/',$str,$match);
    
    echo "<pre>";
    print_r($match);
    
    echo $match['file'];