How to extract only part of string in PHP?

前端 未结 3 1421
难免孤独
难免孤独 2021-01-22 18:51

I have a following string and I want to extract image123.jpg.

..here_can_be_any_length \"and_here_any_length/image123.jpg\" and_here_also_any_length
3条回答
  •  野性不改
    2021-01-22 19:07

    What about something like this :

    $str = '..here_can_be_any_length "and_here_any_length/image123.jpg" and_here_also_any_length';
    $m = array();
    if (preg_match('#".*?/([^\.]+\.(jpg|jpeg|gif|png))"#', $str, $m)) {
        var_dump($m[1]);
    }
    

    Which, here, will give you :

    string(12) "image123.jpg" 
    

    I suppose the pattern could be a bit simpler -- you could not check the extension, for instance, and accept any kind of file ; but not sure it would suit your needs.


    Basically, here, the pattern :

    • starts with a "
    • takes any number of characters until a / : .*?/
    • then takes any number of characters that are not a . : [^\.]+
    • then checks for a dot : \.
    • then comes the extension -- one of those you decided to allow : (jpg|jpeg|gif|png)
    • and, finally, the end of pattern, another "

    And the whole portion of the pattern that corresponds to the filename is surrounded by (), so it's captured -- returned in $m

提交回复
热议问题