Created
May 20, 2010 09:43
-
-
Save simme/407402 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Search a block of text for a given text string | |
* | |
* @param string $pattern | |
* A regexp to match against | |
* @param string|array $input | |
* A string or array (can't handle recursiveness) to search | |
* @param int $context | |
* Returns x number of lines surrounding the hit | |
* @return string $output | |
*/ | |
function grep($pattern, $input, $context = 0) { | |
if (is_string($input)) { | |
$input = explode("\n", $input); | |
} | |
if (!is_array($input)) { | |
throw new InvalidArgumentException('Invalid input must be string or array.'); | |
} | |
$output = array(); | |
foreach ($input as $line => $string) { | |
if (preg_match($pattern, $string)) { | |
if ($context > 0) { | |
$start = ($line - $context < 0) ? 0 : $line - $context; | |
$end = ($line + $context > count($input)) ? count($input) - 1 : $line + $context; | |
$o = ''; | |
for ($start; $start <= $end; $start++) { | |
$o .= $start + 1 . ': ' . $input[$start] . "\n"; | |
} | |
$output[] = "\n" . $o; | |
} | |
else { | |
$output[] = $line + 1 . ': ' . $string; | |
} | |
} | |
} | |
$output = (empty($output)) ? FALSE : join($output, "\n\n----------------------\n\n"); | |
return $output; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment