define('OWNER_POSITION', 7); /** * Prints a message when $searchString appears in the plate number * or in the owner part of $line * @param string $line * @param string $searchString * @return void */ function inspectLine($line, $searchString) { $pos = stripos($line, $searchString); if ($pos !== false) { $plate = substr($line, 0, OWNER_POSITION - 1); $owner = substr($line, OWNER_POSITION); if ($pos < OWNER_POSITION) { echo $plate . ' is the plate number of ' . $owner . PHP_EOL; } else { echo $owner . ' is the owner of plate ' . $plate . PHP_EOL; } } } if ($argc > 1) { while (!feof(STDIN)) { $line = trim(fgets(STDIN)); // If you don't trim, you keep some EOL-char inspectLine($line, $argv[1]); } } else { echo 'Insuffucient parameters. Please supply a search string parameter.' . PHP_EOL; } // EOF
<?php /** * Start of the name */ define('START', 7); $query = $argv[1]; $file = file('php://stdin'); // echo print_r($file); /** * @param string the line to inspect * @param string the query to check for * @return string the owner of a certain plate or the plate of a certain owner containing the search string */ function inspectLine($line, $query) { $pos = stripos($line, $query); if ($pos !== false) { if ($pos < START) { return substr($line, 0, START - 1) . ' is the plate of ' . trim(substr($line, START)) . PHP_EOL; } else { return trim(substr($line, START)) . ' is the owner of ' . substr($line, 0, START - 1) . PHP_EOL; } } } /** * Do inspectLine for each line of the file */ for ($i = 0; $i < count($file); $i++) { echo inspectLine($file[$i], $query); }