开发者

Regex to extract timestamp from a text in PHP

I have the following bit of text (or some similar variation of it):

Recurring Event

First start: 2010-09-16 17:00:00 EDT

Duration: 4800

Event Status: confirmed

I need to select the timestamp of the "First Start" field and the duration.

Normally I 开发者_开发问答would split the string at the colons, but since the timestamp contains them, it sort of becomes problematic. I'm not so good with regular expressions, but does anyone know one that will be able to select the two bits of data I need?

cheers, Mike


Assuming the format stays this way you can search for ": ", i.e. a colon followed by a space. The string following this would be your data.


For a simple non-regex solution, find the first : with strpos($input, ":"), then the rest of the line will have the value.


$content = '

    Recurring Event

    First start: 2010-09-16 17:00:00 EDT

    Duration: 4800

    Event Status: confirmed
';

$contentArray = explode('EDT' , $content);
$head = trim($content[0]);   
//$head will contain 'Recurring Event First start:2010-09-16 17:00:00 '

$headArray = explode(' ' , $head);
$timeStamp = trim(end($headArray));   //which will have 17:00:00


You can do:

if(preg_match('/First start: ([-\d :]+)/',$input,$m)) {
        $timeStamp = trim($m[1]);
}else{
        $timeStamp = '';
}

if(preg_match('/Duration: (\d+)/',$input,$m)) {
        $duration = $m[1];
}else{
        $duration = '';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜