繁体   English   中英

strtotime()的bug

[英]Bug with strtotime()

Simple HTML DOM库用于从网页中提取时间戳。 然后使用strtotime将提取的时间戳转换为MySQL时间戳。

问题:strtotime()在有效时间戳上使用时,返回NULL (参见2: :)。 但是,当第二个示例中未使用Simple HTML DOM时,一切正常。

发生了什么,以及如何解决这个问题?

输出:

1:2013-03-03, 12:06PM
2:
3:1970-01-01 00:00:00

后续代码var_dump($时间)

string(25) "2013-03-03, 12:06PM"

PHP

include_once(path('app') . 'libraries/simple_html_dom.php');

// Convert to HTML DOM object
$html = new simple_html_dom();
$html_raw = '<p class="postinginfo">Posted: <date>2013-03-03, 12:06PM EST</date></p>';
$html->load($html_raw);

// Extract timestamp
$time = $html->find('.postinginfo', 0);
$pattern = '/Posted: (.*?) (.).T/s';
$matches = '';
preg_match($pattern, $time, $matches);
$time = $matches[1];

echo '1:' . $time . '<br>';
echo '2:' . strtotime($time) . '<br>';
echo '3:' . date("Y-m-d H:i:s", strtotime($time));

第二个例子

PHP(工作,没有简单的HTML DOM)

// Extract posting timestamp
$time = 'Posted: 2013-03-03, 12:06PM EST';
$pattern = '/Posted: (.*?) (.).T/s';
$matches = '';
preg_match($pattern, $time, $matches);
$time = $matches[1];

echo '1:' . $time . '<br>';
echo '2:' . strtotime($time) . '<br>';
echo '3:' . date("Y-m-d H:i:s", strtotime($time));

输出(正确)

1:2013-03-03, 12:06PM
2:1362312360
3:2013-03-03 12:06:00

后续代码var_dump($时间)

string(19) "2013-03-03, 12:06PM"

根据你的var_dump() ,从HTML代码中提取的$time字符串长度为25个字符。

看到的字符串"2013-03-03, 12:06PM"只有19个字符。

那么,这6个额外的角色在哪里? 嗯,这很明显,真的:你要解析的字符串真的是"<date>2013-03-03, 12:06PM" 但是当您将其打印到HTML文档中时,浏览器会将<date>解析为HTML标记。

要查看它,请使用浏览器中的“查看源”功能。 或者说,还没有更好的 ,使用htmlspecialchars()打印已不应该包含HTML代码的任何变量时。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM