phpstringtext-extraction

Get substring between first and last underscore in a filename string


I have string named File_Test_name_1285931677.xml. File is the common word and 1285931677 is a random number. I want to remove File_ and _1285931677.xml, i.e. prefix up to first _ and suffix from last _ on.


Solution

  • You can do this with explode, array_slice and implode:

    implode('_', array_slice(explode('_', $str), 1, -1))
    

    With explode the string gets cut into parts at _ so that the result is an array like this:

    array('File', 'Test', 'name', '1285931677.xml')
    

    With array_slice everything from the second to the second last is grabbed, e.g.:

    array('Test', 'name')
    

    This is then put back together using implode, resulting in:

    Test_name
    

    Another approach would be to use strrpos and substr:

    substr($str, 5, strrpos($str, '_')-5)
    

    Since File_ has fixed length, we can use 5 as the starting position. strrpos($str, '_') returns the position of the last occurrence of _. When subtracting 5 from that position, we get the distance from the fifth character to the position of the last occurrence that we use as the length of the substring.