How to find and extract date in string with php?

by herminia_bruen , in category: PHP General , a year ago

How to find and extract date in string with php?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by gilbert , a year ago

@herminia_bruen 

There are multiple ways to find and extract a date from a string using PHP. Here are a few examples:

  1. Regular Expressions: You can use regular expressions to match and extract the date pattern from a string. For example:
1
2
3
4
5
6
7
$string = "Today is 25-11-2021";
$pattern = "/d{2}-d{2}-d{4}/";  // Matches date in format DD-MM-YYYY

preg_match($pattern, $string, $matches);
$date = $matches[0];  // Extracted date from the string

echo $date;  // Output: 25-11-2021


  1. strtotime() function: If the date in the string is in a recognizable format, you can use the strtotime() function to convert it to a Unix timestamp and then format it as desired. For example:
1
2
3
4
5
6
7
8
9
$string = "Today is November 25, 2021";

// Remove non-alphanumeric characters and extra spaces from the string
$string = preg_replace('/[^a-zA-Z0-9s]/', '', $string);

// Extract date using strtotime()
$date = date("Y-m-d", strtotime($string));

echo $date;  // Output: 2021-11-25


  1. DateTime class: You can utilize the DateTime class to parse and extract the date from the string. Here's an example:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$string = "Today is 25th November, 2021";

// Remove non-alphanumeric characters and extra spaces from the string
$string = preg_replace('/[^a-zA-Z0-9s]/', '', $string);

// Extract date using DateTime class
$date = DateTime::createFromFormat("j F, Y", $string);
$dateFormatted = $date->format("Y-m-d");

echo $dateFormatted;  // Output: 2021-11-25


Note: The approach may vary depending on the format and structure of the string you have. You may need to modify the regular expressions or the format used in strtotime() or DateTime::createFromFormat() to match your specific requirements.

Member

by daisha , a year ago

@herminia_bruen 

Additionally, you can use the preg_match_all() function to find and extract multiple dates from a string. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
$string = "The event dates are 2021-12-01 and 2022-01-15";

$pattern = "/d{4}-d{2}-d{2}/";  // Matches dates in format YYYY-MM-DD

preg_match_all($pattern, $string, $matches);

$dates = $matches[0];  // Extracted dates from the string

foreach ($dates as $date) {
    echo $date . "<br>";  // Output: 2021-12-01, 2022-01-15
}


In this example, the preg_match_all() function is used with a regular expression pattern to find all occurrences of dates in the format "YYYY-MM-DD" in the given string. The extracted dates are stored in the $dates array, which can be accessed and processed as needed.