Search code examples
phppreg-matchcontent-disposition

Extracting filename from content disposition via PHP


I need a regex to extract the filename (incl. file extension) from the following string:

attachment; filename*=UTF-8''test.rar

or like this

attachment; filename*=UTF-8''Epost%20-test.part01.rar

Target:

test.rar
Epost%20-test.part01.rar

How can I do this?

Note: I'm using preg_match for extracting


Solution

  • This should work for you:

    <?php
    
        $str = "attachment; filename*=UTF-8''test.rar";
    
        preg_match_all("/\w+\.\w+/", $str, $output);
    
        echo $output[0][0];
    
    ?>
    

    Output:

    test.rar
    

    EDIT:

    If the 2 single quotes are every time in the string you can grab every thing after with:

    <?php
    
        $str = "attachment; filename*=UTF-8''Epost%20-test.part01.rar";
    
        preg_match_all("/[^\'\']+$/", $str, $output);
    
        echo $output[0][0];
    
    ?>
    

    Output:

    Epost%20-test.part01.rar