PHP regular expression to extract timestamps and comments

I have several exported text fields from an old access database that are migrated to the new mysql structure. There are various field inputs in the format:

06/10/2010 09:10:40 Work has not yet begun

I would like to take this line and use some kind of regular expression to retrieve the date / time information and the subsequent comment.

Is there a simple regular expression syntax for matching this information?

thank

+3
source share
9 answers

I think I will have this

preg_match('|^([0-9]{2})/([0-9]{2})/([0-9]{4})\s([0-9]{2}):([0-9]{2}):([0-9]{2})\s(.*)$|',$str,$matches);
list($str,$d,$m,$y,$h,$m,$s,$comment)=$matches;

then you have the necessary values ​​to restore time in any format.

+2
source

:

$parts = explode(" ", $string, 3);
+7

, , :

/([^ ]+) ([^ ]+) (.+)/

: , , ( ).

+3

. , 2 2 :

$str = "10/06/2010 09:10:40 Work not yet started";
$slices = explode(" ", $str, 3);
$timestamp = strtotime($slices[0] . $slices[1]);
echo "String is $str\n";
echo "Timestamp is $timestamp\n";
echo "Timestamp to date is " . strftime("%d.%m.%Y %T", $timestamp) . "\n";
+2

, / datetime, -

preg_match("/^([0-9\\/]{10} [0-9:]{8}) (.*)$/",$str,$matches);
$datetime = $matches[1];
$description = $matches[2];

/ ,

preg_match("/^([0-9\\/]{10}) ([0-9:]{8}) (.*)$/",$str,$matches);
$date = $matches[1];
$time = $matches[2];
$description = $matches[3];

, :

list($date,$time,$description) = explode(' ',$str,3);

, :

$date = substr($str,0,10);
$time = substr($str,11,19);
$description = substr($str,20);
+1
if(preg_match('([0-9/]+ [0-9:]+)', $myString, $regs)) {
  $myTime = strtotime($regs[1]);
}
0

2 , :

([0-9]{1,2}\/[0-9]{1,2}\/[0-9]{4}\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2})\s(.*)
0

:

// sample string you provided
$string = "10/06/2010 09:10:40 Work not yet started";

// regular expression to use
$regex = "/^(\d+)\/(\d+)\/(\d+) (\d+)\:(\d+)\:(\d+) (.+?)$/";

, , $matches. $array, preg_match()

// method 1: just extract
preg_match($regex, $string, $matches);

// method 2: to check if the string matches the format you provided first
//           then do something with the extracted text
if (preg_match($regex, $string, $matches) > 0) {
   // do something
}

:

// to get a Unix timestamp out of the matches
// you may use mktime()

// method 1: supposed your date format above is dd/mm/yyyy
$timestamp = mktime($matches[4], $matches[5], $matches[6], 
  $matches[2], $matches[1], $matches[3]);

// method 2: or if your date format above is mm/dd/yyyy
$timestamp = mktime($matches[4], $matches[5], $matches[6], 
  $matches[1], $matches[2], $matches[3]);

, :

print date('r', $timestamp)

, :

$comment = $matches[7];

. , , , , . , / .

0
$s = '10/06/2010 09:10:40 Work not yet started';
$date = substr($s, 0, 19);
$msg = substr($s, 20);

$date = strtotime($date);
// or
$date = strptime($date, "%m/%d/%Y %H:%M:%S");
0
source

Source: https://habr.com/ru/post/1751003/


All Articles