0
votes

I have a string like this:

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...

I would like to get all the dates inside the text... the format dates are always yyyy-mm-dd.

Any suggestions?

3
At Stack Overflow you are expected to try to write the code yourself. After doing more research if you have a problem you can post what you've tried with a clear explanation of what isn't working and providing a Minimal, Complete, and Verifiable example. I suggest reading How to Ask a good question and the perfect question. Also, be sure to take the tour. - John Conde
try regular expressions, get the right pattern to match the dates and then use that pattern within the preg_match function , see php.net/manual/en/function.preg-match.php - John Cogan

3 Answers

1
votes

Try to use preg_match and regex expression:

$string = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean 2017-03-31 ligula eget dolor. Aenean massa. 2016-03-04 sociis natoque penatibus...";
$pattern = '/([0-9]{4}-[0-9]{2}-[0-9]{2})/';
preg_match_all($pattern, $string, $matches);
print_r($matches);

To test regex, I suggest you to use https://regex101.com/

1
votes
preg_match("/[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}/", $input_line, $output_array);
1
votes

Alright so what you have to do is figure out what you are trying to find, in your case yyyy-mm-dd.

So this would be it:

[0-9]{4}-[0-9]{2}-[0-9]{2}