Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@simme
Created May 20, 2010 09:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simme/407402 to your computer and use it in GitHub Desktop.
Save simme/407402 to your computer and use it in GitHub Desktop.
<?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