Bolte
Bolte

Reputation: 141

PHP extract date from filename returned in foreach

Using PHP given that I have a foreach loop going through via glob to output some images, I would like to extract the date and time the images were uploaded.

I have them named as follows when they are uploaded:

1234567_29052017-122959.jpg

The first sequence of numbers before the _ is an account number, this is to be stripped out. The second sequence of numbers is the date, so 29/05/2017. The third sequence of numbers is the time of day, so 12:29:59. Each filename is output as $image in the foreach below:

$dirname = 'photos/' . $account . '/';
$images = glob($dirname.'*.jpg');

If ($images == null ) {
    echo "There was no photos returned for the account number that you entered.";
} else {

    foreach($images as $image) {
        echo '
            <div class="viewerContent" style="width:220px; min-height: 160px;">Insert Date Here <br />
            <a href="'.$image.'"><img src="'.$image.'" width="220" height="160" title="'.$image.'" /></a><br />
            </div>';
    }   

}               

What I want to is extract the following from the above given example.

1234567_29052017-122959.jpg

To

29/05 12:29:59s 

Can anyone assist me in achieving this?

I am going to add the resulting timestamp to the foreach in the Insert Date Here section of the repeating echo.

Upvotes: 1

Views: 577

Answers (2)

Curious Mind
Curious Mind

Reputation: 659

Yes, explode it like this to get the date:

// Assuming a filename like this "1234567_29052017-122959.jpg"
$filedate = explode('_',$filename)[1];
$filehour = substr(explode('-',$filename)[1], 0, -3);

To convert your string to date:

function reformatDate($date, $from_format = 'dmY', $to_format = 'd/m') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}

For your time, if the format is always the same - don´t check the content and split it 2 chars by 2:

$outputString = chunk_split($string, 2, ":");

Hope this helps.

Upvotes: 0

Andreas
Andreas

Reputation: 23958

$subst = '$1/$2/ $4:$5:$6';
$pattern = '/.*_(\d{2})(\d{2})(\d{4})-(\d{2})(\d{2})(\d{2})/g';
$new = preg_replace($pattern, $subst, $oldstr);

https://regex101.com/r/Pxn2jr/1

Edit forgot the substitute.

Upvotes: 2

Related Questions