Picking date and time from a string

4

I want to "filter" string to get only the date that is in it, string is in that format:

  

SSC Napoli v Dnipro - Thursday 05/07/2015 04:05 PM

What I want to get is just 07/05/2015 16:05 , I used 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, type:

  

SSC Napoli2 v Dnipro - Thursday 5/7/2015 4:05 PM

Obviously it will go wrong, I wanted to use something in regex if I had how to extract that date and time, I am weak in regex and already tried some things but it did not work!

Update :

I was able to make use of the following algorithm as well:

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

But if someone has something more elaborate, please answer!

    
asked by anonymous 09.05.2015 / 01:23

2 answers

4

You can use this regex to capture the date, use the preg_match or preg_match_all since eregi_* has been deprecated 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}\/)+ This group (parentesses content) captures the day and month and the bar. \d allows only the digits to be captured, {2} means the number of captures.

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

(\d{2}:\d{2}) Captures the time that is made up of two digits ( \d{2} ) followed by colon and finally two more digits.

    
09.05.2015 / 01:43
2

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

$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 retrieve 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

    
09.05.2015 / 02:11