Вопрос

I have two different strings:

  • Baby 14% 28.07.2012
  • Hello 2% 15.06.16 Ten

("baby" or "14%" or "ten" can change, so i can't specify them)

I want to recognize the date inside that string and i tried with:

$dt = date_parse($string);

In the first case, it's ok, but in the second one it doesn't recognize the date.

I tried with no success

$dt = date_parse_from_format("d.m.Y", $string);

and I tried with preg_match or preg_match_all with no success (i'm not very good at it).

Это было полезно?

Решение

You can catch the dates with a regular expression, for example :

if(preg_match('/(.*)([0-9]{2}\.[0-9]{2}\.[0-9]{2,4})(.*)/', $yourString, $matches))
{
 $date = $matches[2];
}

Другие советы

You mention that baby, 14% and Ten can change. But is it always a single word/value? If so you could use:

$split = explode(' ', $string)
$date = $split[2];

//$split[0] = Baby
//$split[1] = 14%
//$split[2] = 28.07.2012

//$date = 28.07.2012

//$split[0] = Hello
//$split[1] = 2%
//$split[2] = 15.06.16
//$split[3] = Ten

//$date = 15.06.16

I liked aurel.g's answer and expanded it some for my own purposes. In particular, I wanted to handle the two-digit years that Excel keeps converting my good dates into. I also used strtotime() to return FALSE if the date was bunk (like 6/32/2014). I thought this might be helpful (and I didn't find a way to post this as a comment above, sorry):

$result = preg_match("/^(.*)(\d{1,2}\/\d{1,2}\/\d{2,4})(.*)/",$date, $matches);
// use strtotime() to test if that's a valid date:
if ($result && strtotime($matches[2]) {
  // convert it back to the date in the desired format:
  return date('m/d/Y',strtotime($matches[2]));
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top