Fun with regular expressions: 🙂
<?php
$input = "start
ckmb52fldxkseven3fkjgcbzmnr7
gckhqpb6twoqnjxqplthree2fourkspnsnzxlz1
2onetwocrgbqm7
frkh2nineqmqxrvdsevenfive
four9two";
$numbers = [];
foreach(preg_split('/\r?\n/', $input) as $line) {
preg_match('/^[^\d]*(\d).*(\d)[^\d]*$/', $line, $matches);
if(!empty($matches)) {
$numbers[] = (int) $matches[1].$matches[2];
}
}
echo "Found these numbers: ".implode(', ', $numbers)."\n";
echo "The total is: ".array_sum($numbers)."\n";
Result:
$ php ~/Desktop/challenge.php
Found these numbers: 57, 61, 27
The total is: 145