1

我有一个 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% 确定正则表达式是否可行?

4

2 回答 2

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";
}

请参阅演示以查看哪些变量分配给文件中的哪些值。

于 2012-06-23T01:43:24.300 回答
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] => 00:00:50,784 --> 00:00:54,117 我觉得很高兴我们正在做一些 Maggie 会喜欢的事情。[2] => 00:00:54,220 --> 00:00:58,350 此外,我相信 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}')");
}
于 2012-06-23T02:01:48.537 回答