Pick date and time from a string

Asked

Viewed 1,907 times

4

I’m looking to "filter" the string to obtain only the date that is on it, the string is in that format:

SSC Napoli v Dnipro - Thursday 07/05/2015 16:05 Hours

The I want to take is just the 07/05/2015 16:05, used the explode:

$datas = eregi_replace('[.\A-Z\-]','', $datas);
$datas = explode("/",trim($datas));
$dia = substr($datas["0"], -2);
$datas = $dia."/".$datas["1"]."/".$datas["2"]."";
return $datas;

But the problem is that when the name of the team that is in the string has number, like:

SSC Napoli2 v Dnipro - Thursday 07/05/2015 16:05 Hours

Obviously it will go wrong, wanted to wear something in regex if I could, to extract this date and time, I am weak in regex and I’ve tried some things but it didn’t work!

Updating:

I was able to make it work also using the following algorithm:

eregi_replace('[.\A-Z\-]','',substr($_GET["link"],-22));

But if anyone has anything more elaborate, please respond!

  • Killed the stick!!! thanks! needed to search the year in a text field

2 answers

5


You can use that regex to capture the date, use the function preg_match or preg_match_all, for eregi_* was depreciated from php 5.3

$str = 'SSC Napoli v Dnipro - Quinta-Feira 07/05/2015 16:05 Horas';
preg_match('/(\d{2}\/)+(\d{4})\s*(\d{2}:\d{2})/', $str, $match);
echo '<pre>';
print_r($match);

echo 'data completa: '. $match[0];

Example - Ideone

Explanation:

(\d{2}\/)+ That group(the parent content) captures the day and month and the bar. \d only allows digits to be captured, {2} means that the number of catches.

(\d{4})\s* This group captures the year following one or more spaces(\s*)

(\d{2}:\d{2}) Captures the time that is composed of two digits(\d{2}) followed by two dots and then two more digits.

2

An alternative regular expression: (\d{2})-. /[-. /]+( d{4}) s([ d:]+).

$texto = "SSC Napoli v Dnipro - Quinta-Feira 07/05/2015 16:05 Horas
          SSC Napoli v Dnipro - Quinta-Feira 08-06-2015 17:05 Horas
          SSC Napoli v Dnipro - Quinta-Feira 09.06.2015 18:05 Horas";

preg_match_all('~(\d{2})[-.\/](\d{2})[-.\/]+(\d{4})\s([\d:]+)~', $texto, $data);

To recover the values do:

foreach($datas[0] as $data) echo "Data completa: {$data}\n";
foreach($datas[1] as $dia)  echo "Dia encontrado: {$dia}\n";
foreach($datas[2] as $mes)  echo "Dia encontrado: {$mes}\n";
foreach($datas[3] as $ano)  echo "Ano encontrado: {$ano}\n";
foreach($datas[4] as $horario) echo "Horário encontrado: {$horario}\n";

DEMO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.