如何在PHP中从字符串中获取特定值

如何在PHP中从字符串中获取特定值,php,Php,我想从下面的第一句和第二句[括号内]中得到时间,然后在一分钟内看到差异。例如,在本例中,结果为1分钟 [04:38:41] Preflight started, flying offline [04:39:29] Pushing back with 7512 kg of fuel 如果您能帮助我了解如何在PHP中实现这一点,我将不胜感激 谢谢您可以使用以下示例来获取两者之间的秒数: $datetime1 = strtotime('11:01:00'); $datetime2 = strtoti

我想从下面的第一句和第二句[括号内]中得到时间,然后在一分钟内看到差异。例如,在本例中,结果为1分钟

[04:38:41] Preflight started, flying offline
[04:39:29] Pushing back with 7512 kg of fuel
如果您能帮助我了解如何在PHP中实现这一点,我将不胜感激


谢谢

您可以使用以下示例来获取两者之间的秒数:

$datetime1 = strtotime('11:01:00');
$datetime2 = strtotime('11:00:01');

echo abs($datetime1-$datetime2);

您可以使用以下示例以秒为单位获得差异

$string1 = '[04:38:41] Preflight started, flying offline';
$string2 = '[04:39:29] Pushing back with 7512 kg of fuel';

$datetime1 = substr($string1,4,6); // Getting the time of the first string
$datetime2 = substr($string2,4,6); // Getting the time of the second string

echo abs($datetime1-$datetime2); // Calculating the difference between the two values.
试试这个

<?php
$time1 = explode(':', "04:38:41");
$time2 = explode(':', "04:39:29");
echo $result =  $time2[1] - $time1[1];
?>

或者,你可以从全文开始

<?php
$time1_string = "[04:38:41] Preflight started, flying offline";
$time2_string = "[04:39:29] Pushing back with 7512 kg of fuel";
$time1 = explode(':', $time1_string);
$time2 = explode(':', $time2_string);
echo $result =  $time2[1] - $time1[1];
?>

您也可以通过使用

示例:

<?php
//string 1
$text1 = '[04:38:41] Preflight started, flying offline';
preg_match('/\\[([^\\]]*)\\]/', $text1, $match);
$time1 = $match[1]; // will return 04:38:41

//string 2
$text2 = '[04:39:29] Pushing back with 7512 kg of fuel';
preg_match('/\\[([^\\]]*)\\]/', $text2, $match);
$time2 = $match[1]; // will return 04:39:29

// check difference
$diff = abs(strtotime($time2) - strtotime($time1));
echo $diff; // will return 48 seconds
?>


到目前为止,您尝试了什么?您是否在解析字符串或计算时差时遇到困难?您可以使用
preg_match()
使用regex模式捕获时间您的预期结果是错误的。感谢分享,但您没有提到如何从字符串中获取时间。这只会将字符串更改为时间。请检查。请注意,您需要使用“preg\u match”而不是“preg\u match\u all”