[2015-03-02] Challenge #204 [Easy] Remembering your lines

PHP

Does not satisfy the bonus, but gets the job done otherwise. The verse being searched for is taken as a command line argument.

<?php
define("FILE", "macbeth.txt");

$macbeth = file_get_contents(FILE);
$verse = $argv[1];
$result_passage = '';
$pos = 0;
$start = 0;
$end = 0;

$lines = explode("\n", $macbeth);

foreach ($lines as $line_number => $line) {
    $pos = strpos($line, $verse);
    if ($pos) {
        $i = 1;
        while (strpos($lines[$line_number - $i], "    ") === 0) {
            $i++;
        }
        $start = $line_number - ($i - 1);
        $i = 1;
        while (strpos($lines[$line_number + $i], "    ") === 0) {
           $i++;
        }
        $end = $line_number + ($i - 1);
        break;
    }
}

for ($count = $start ; $count <= $end ; $count++) {
    if ($count == $end)
        $result_passage .= $lines[$count];
    else
        $result_passage .= $lines[$count] . PHP_EOL;
}


echo $result_passage. PHP_EOL;
exit();

Challenge Inputs:

1: break this enterprise

output : What beast was't, then, That made you break this enterprise to me? When you durst do it, then you were a man; And, to be more than what you were, you would Be so much more the man. Nor time nor place Did then adhere, and yet you would make both: They have made themselves, and that their fitness now Does unmake you. I have given suck, and know How tender 'tis to love the babe that milks me: I would, while it was smiling in my face, Have pluck'd my nipple from his boneless gums And dash'd the brains out, had I so sworn as you Have done to this.

2: Yet who would have thought

output: Out, damned spot! out, I say! One; two; why, then 'tis time to do't ; Hell is murky! Fie, my lord, fie! a soldier, and afeard? What need we fear who knows it, when none can call our power to account? Yet who would have thought the old man to have had so much blood in him?

/r/dailyprogrammer Thread