<?php
$iterations = 5000;
$string = "HD Alcoa Earnings Soar; Outlook Stays Upbeat
BY By James R. Hagerty and Matthew Day
PD 12 July 2011
LP
Alcoa Inc.'s profit more than doubled in the second quarter.
The giant aluminum producer managed to meet analysts' forecasts.
However, profits wereless than expected
TD
Licence this article via our website:
http://example.com";
## OUTPUT FORMAT & BENCHMARK CODE
# SWEETIE BELLE
echo "-----\n";
echo strtoupper("Sweetie Belle's solution (uses regexp):\t\t");
$benchmark_start = microtime(true);
for($i=0;$i<$iterations;$i++) sb_headerSplit($string);
echo round(microtime(true) - $benchmark_start, 3) . " seconds\n";
var_dump(sb_headerSplit($string));
echo "\n";
# HEK2MGL
echo "-----\n";
echo strtoupper("Hek2mgl's solution (uses regexp):\t\t");
$benchmark_start = microtime(true);
for($i=0;$i<$iterations;$i++) answer_1($string);
echo round(microtime(true) - $benchmark_start, 3) . " seconds\n";
var_dump(answer_1($string));
echo "\n";
## FUNCTIONS BELOW, DO NOT EDIT
function sb_headerSplit($input) {
preg_match_all("/^[A-Z]{2}/m",$input,$matches);
$split = preg_split("/^[A-Z]{2}/m",$input,null,PREG_SPLIT_NO_EMPTY);
$result = array();
foreach($matches[0] as $key => $value) $result[$value] = preg_replace("/[\n\r]/"," ",trim($split[$key]));
return $result;
}
function answer_1($input) {
$record = array();
//foreach(file('input.txt') as $line) {
foreach($input AS $line) {
if(preg_match('~^(HD|BY|PD|LP|TD) ?(.*)?$~', $line, $matches)) {
$currentKey = $matches[1];
$record[$currentKey] = $matches[2];
} else {
$record[$currentKey] .= str_replace("\n", ' ', $line);
}
}
return $record;
}
preferences:
59.18 ms | 402 KiB | 5 Q