Im trying to extract subtitle entries out of a SRT file. Ive written a script that opens the file and with the help of regex fetches the strings. Ive testes the regex pattern on regex101.com using the correct php engine. And it works. For some reason php CLI has an issue with the pattern. It seems that newlines "\n" in the pattern is either causing the problem or the imported file strips all newlines.
here is the regex pattern
^(?<NR>\d+)\n(?<START>\d\d:\d\d:\d\d,\d\d\d)(?>\s?-->\s?)(?<END>\d\d:\d\d:\d\d,\d\d\d)\n(?<STRING>(?>.+\n?)+)
Dummy text:
1 00:00:46,296 --> 00:00:50,425 They were startled and frightened, thinking they saw a ghost. 2 00:00:50,467 --> 00:00:52,386 He said to them, 3 00:00:54,179 --> 00:00:57,140 "Why are you troubled, and why do doubts rise in your minds? 4 00:00:57,182 --> 00:00:59,977 <i>Look at my hands and my feet. It is I myself!</i>
PHP code
<?php $path1 = $argv[1]; $file1_content = file_get_contents($path1); $pattern = '%^(?<NR>\d+)\n(?<START>\d\d:\d\d:\d\d,\d\d\d)(?>\s?-->\s?)(?<END>\d\d:\d\d:\d\d,\d\d\d)\n(?<STRING>(?>.+\n?)+)%'; $success = preg_match_all($pattern, $file1_content, $matches); var_dump($matches);
CLI Instructions
-
open a text file and save the dummy content into it.
-
Open your shell and goto dir of txt file.
-
type %php -f [php-script-file] -- [full-path-to-dummy-file]
Your regex pattern needs some delimiters.
if(preg_match("#(\d{1,2})\:(\d{2})#", "5:00", $matches) == 1) echo "works";
else echo "don't work";
You need to put your regular expression within delimiters:
if(preg_match("/(\d{1,2}):(\d{2})/", "5:00", $matches) == 1) echo "works";
else echo "don't work";
Also, you don't need to escape the :, but it works either way.