Skip to content

Instantly share code, notes, and snippets.

@ryan-allen
Created February 2, 2011 05:32
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 ryan-allen/807289 to your computer and use it in GitHub Desktop.
Save ryan-allen/807289 to your computer and use it in GitHub Desktop.
recursive string scanner
<?php
function scan_until($subject, $search, $position = 0, $match_position = 0, $buffer = '') {
$char = substr($subject, $position, 1); // take of a character
$position += 1; // increment our subject position
if ($position == strlen($subject)) { // are we at the end and haven't found shit?
return $subject;
}
if ($char == substr($search, $match_position, 1)) { // have we matched anything?
$match_position += 1; // we got a match, quick increment!
} else {
$match_position = 0; // no match this run, so reset the position, it's all or nothing!
}
if ($match_position > 0 && strlen($search) == $match_position) { // is the match completed?
return substr($buffer, 0, -strlen($search)+1); // return the buffer, but take the search off the end
}
return scan_until($subject, $search, $position, $match_position, $buffer . $char); // keep looking recursively
}
echo "'" . scan_until('I like to eat lollies.', 'lollies') . "'\n"; // => 'I like to eat '
echo "'" . scan_until('I like to eat lollies.', 'poop') . "'\n"; // => 'I like to eat lollies.'
echo "'" . scan_until('I like to eat lollies.', 'too') . "'\n"; // => 'I like to eat lollies.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment