there is a test file of the form

(0:00) text1 text2 (0:30) text text text text text .................. 

you need to get an array of the form key - this is the value in brackets, and the value is a test.

 array("(0:00)"=>"text1 text2","(0:30)"=>"text text text text text") 

I write the following:

  $key = array(); $val = array(); $out = array(); $file = file('1.txt'); foreach($file as $line) { $line = trim($line); if (preg_match("/(\d{0,2}:\d\d)/",$line,$match)){ $key[]=$match; }else{ $val[]=$match; } $out=array_merge($key,$val); } echo '<pre>'; print_r($out); 

tell me how to fix?

  • preg_match_all - toxxxa

3 answers 3

If you still extract the entire contents of the file using the file() function into RAM, can you then do without an array? Extract the contents of the file into a single line using the file_get_contents() function. It will be much more convenient to get all entries, for example, using preg_match_all() , and then, based on the response received (below is $results ), generate the $out array you need

 <?php $out = array(); $file = file_get_contents('1.txt'); preg_match_all("/(\(\d{0,2}:\d{2}\))([^\(]+)/", $file, $results); foreach($results[1] as $key => $value) { $out[$results[1][$key]] = $results[2][$key]; } echo '<pre>'; print_r($out); 
     $key = ''; $val = array(); $out = array(); $file = file('1.txt'); foreach($file as $line) { $line = trim($line); if (preg_match("/(\d{0,2}:\d\d)/",$line,$match)){ $key = $match; }else{ $val[$key][] = $match; } } foreach($val as $k=>$v) $val[$k] = implode(' ',$v); echo '<pre>'; print_r($val); 
    • Warning: Illegal offset type on line 11 - G_test_00
     $text = file_get_contents('1.txt'); preg_match_all("~\(\d{1,2}:\d{1,2}\)~", $text, $keys); $values = array_values(preg_grep("~.+~", preg_split("~\(\d{1,2}:\d{1,2}\)~", $text))); $final = []; for ($n = 0; $n < count($keys[0]); $n++) { $final[$keys[0][$n]] = $values[$n]; } print_r($final);