Created
February 2, 2011 05:32
-
-
Save ryan-allen/807289 to your computer and use it in GitHub Desktop.
recursive string scanner
This file contains hidden or 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 | |
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