Search code examples
phptext-extractionstring-parsing

Get substrings after each colon-ended label from a string without delimiters


I have the following string in PHP.

"File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124"

I need to fetch file, date, and size separately.

What is the best way to extract the required values?

explode() OR substring()

Explode requires some common value, substring requires start and end. In both cases I am a bit confused.


Solution

  • Try this:

    <?php
    $text = "File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124";
    $pattern = '/file:(.*?)date:(.*?)size:(.*)/i';
    preg_match($pattern, $text, $out);
    print_r($out);
    ?>
    

    Output:

    Array
    (
        [0] => File:content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpgDate:Fri Mar 18 11:30:17 CET 2016Size:23124 
        [1] => content/resources/11933/Calm_Nebula_by_The_Free_Mason.jpg
        [2] => Fri Mar 18 11:30:17 CET 2016
        [3] => 23124
    )
    

    Demo: https://3v4l.org/OcSXH