Answer ⏱ 16ms
Part 1 :
53334
Part 2 :
52834
function solve($lines) {
return $lines->map(function ($l) {
$nums = $l->chars()->keep(range(0, 9));
return (int) ($nums->first() . $nums->last());
})->sum();
}
// ==================================================
// > PART 1
// ==================================================
$solution_1 = solve($input->lines);
// ==================================================
// > PART 2
// ==================================================
$digits = [
"zero" => 0,
"one" => 1,
"two" => 2,
"three" => 3,
"four" => 4,
"five" => 5,
"six" => 6,
"seven" => 7,
"eight" => 8,
"nine" => 9,
];
$solution_2 = solve($input->lines->map(fn ($l) =>
scalar(preg_replace_callback("/(".implode("|", array_keys($digits)).")/", fn ($r) =>
$digits[$r[1]]
, (string) $l))
));