我有一个SRT文件目录,格式化:
8
00:00:45,879 --> 00:00:50,680
- Oh! Just leave me in the car with the window open a crack.
- That's the plan.
9
00:00:50,784 --> 00:00:54,117
I think it's nice we're doing something
Maggie will enjoy for once.
10
00:00:54,220 --> 00:00:58,350
Besides, I'm sure Storytown Village
is also fun for everyone...
我正在尝试将某些值放入MySQL数据库中,但我完全不知道如何使用正则表达式和php进行操作。
我想第一次(即00:00:50)进入“时间”,并将与该时间相关的任何文本行放入“文本”。
我甚至不能100%确定正则表达式是否可行,如果有更简单的方法可以做到这一点?
答案 0 :(得分:1)
你的文本中有很多分隔符,所以我不会使用正则表达式。这是一个使用字符串操作的解决方案:
$lines = explode( "\n", $str);
for( $i = 0, $ii = count( $lines); $i < $ii; $i += 5) {
$num = trim( $lines[ $i ]);
list( $line2a, $line2b) = explode( ' --> ', $lines[ $i + 1]);
list( $time1, $val1) = explode( ',', $line2a);
list( $time2, $val2) = explode( ',', $line2b);
$text1 = $lines[ $i + 2];
$text2 = $lines[ $i + 3];
echo "$num $time1 $val1 $time2 $val2\n$text1\n$text2\n\n";
}
请参阅the demo,了解哪些变量已分配给文件中的哪些值。
答案 1 :(得分:0)
这种模式可行:
$pattern = '/([\d,:]+) --> [\d,:]+\n(.*\n.*)[^\n\n]/m';
$string = "
8
00:00:45,879 --> 00:00:50,680
- Oh! Just leave me in the car with the window open a crack.
- That's the plan.
9
00:00:50,784 --> 00:00:54,117
I think it's nice we're doing something
Maggie will enjoy for once.
10
00:00:54,220 --> 00:00:58,350
Besides, I'm sure Storytown Village
is also fun for everyone..."; //Your File Contents Here
preg_match_all($pattern, $string, $matches);
print_r($matches);
这将导致:
Array
(
[0] => Array
(
[0] => 00:00:45,879 --> 00:00:50,680
- 哦!只要让我在车窗外打开一个裂缝。 - 那就是计划。 [1] =&gt; 00:00:50,784 - &gt; 00:00:54117 我觉得我们做的很好 Maggie将享受一次。 [2] =&gt; 00:00:54,220 - &gt; 00:00:58350 此外,我很确定Storytown Village 对每个人来说都很有趣...... )
[1] => Array
(
[0] => 00:00:45,879
[1] => 00:00:50,784
[2] => 00:00:54,220
)
[2] => Array
(
[0] => - Oh! Just leave me in the car with the window open a crack.
- That's the plan
[1] => I think it's nice we're doing something
Maggie will enjoy for once
[2] => Besides, I'm sure Storytown Village
is also fun for everyone..
)
)
更新
foreach($matches[1] as $i => $data){
$time = $data;
$message = $matches[2][$i];
mysqli_query("INSERT INTO Table (time,message) VALUES ('{$time}', '{$message}')");
}