0

this is my code that extracts the date "2016-06-13" from the string "ffg_LTE_2016-06-13"

$re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';
$str = "ffg_LTE_2016-06-13";
preg_match($re, $str, $matches);
$date=$matches[0];
print_r($date);

Now what I want to do is do somthing like this in a for loop but I am having issues with storing the result in an array. What I want to do is the same as above but do it on each elememt in the array.

$files=["ffg_LTE_2016-06-13","ffg_LTE_2016-06-14"];

foreach ($files as $value) {
    print_r("<br>".$value."<br>");
}

So my end result would be

$files_2=["2016-06-13","2016-06-14"];

here is my fiddle

1
  • 1
    why not jiust explode on the underscore Commented Jun 21, 2016 at 21:50

1 Answer 1

1

You can try this:

<?php

    $files=["ffg_LTE_2016-06-13","ffg_LTE_2016-06-14"];
    $re = '/(\d{8})|([0-9]{4}-[0-9]{2}-[0-9]{2})|([0-9]{2}-[0-9]{2}-[0-9]{4})/';

    $results = [];
    foreach ($files as $value) {
        preg_match($re, $value, $matches);
        $results[] = $matches[0];
    }
    print_r($results);

?>

It just loops through $files, pushes the first match into the array $results, and prints out $results.

Sign up to request clarification or add additional context in comments.

2 Comments

tks, can you just briefly explain this $results[] = $matches[0]; as I think I was tring to do this $results=$matches[0]or array_push($results,$matches[0]); but maybe I should do this array_push($results[],$matches[0]); I was basically missing the [] in results
@HattrickNZ $results[] = $matches[0]; is equivalent to array_push($results,$matches[0]); as state on the manual page php.net/manual/en/function.array-push.php

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.