1

I need to find all dates in a string and convert them to the format "d.m.Y". I know how to simply convert a date to another format using strtotime() and date(), but how do I convert all dates in a string? For example,

Some text 2018-08-28 11:56:48 .Some text 2017-10-30 07:39:21

will be converted to

Some text 28.08.2018 11:56:48 .Some text 30.10.2017 07:39:21
janw
  • 8,758
  • 11
  • 40
  • 62

2 Answers2

2

You could use preg_replace_callback() with an anonymous callback function to convert the date for you:

$input = "Some text 2018-08-28 11:56:48 .Some text 2017-10-30 07:39:21";
echo preg_replace_callback(
    "/\d{4}-\d{2}-\d{2}/", // Searches for "XXXX-XX-XX", where X represents a decimal digit
    function ($match)
    {
        return date("d.m.Y", strtotime($match[0])); // Parse and re-format matched date
    },
    $input);

(try it)

Output:

Some text 28.08.2018 11:56:48 .Some text 30.10.2017 07:39:21

If you want to match both date and time, you may use the regular expression

/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/

and the format string d.m.Y H:i:s instead.

janw
  • 8,758
  • 11
  • 40
  • 62
0

You can solve this by a single regex replace:

see: https://regex101.com/r/4pmtJH/1

  • pattern: \b(\d{4})-(\d{2})-(\d{2})\b
  • replace: $3.$2.$1
  • flags: gm
Andre Elrico
  • 10,956
  • 6
  • 50
  • 69