Last active
April 3, 2017 09:15
-
-
Save renlight10/c4b89a3c56e32415d962549738efa020 to your computer and use it in GitHub Desktop.
PHP Horspool Algorithm
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 | |
| /** | |
| * PHP implementation Boyer Moore Horspool Algorithm | |
| * | |
| * PHP version 5 | |
| * | |
| * @category Algorithm | |
| * @package Horspool_Algorithm | |
| * @author ren <ren_ice@live.com> | |
| * @copyright 2017 notepy | |
| * @license MIT http://opensource.org/licenses/MIT | |
| * @link https://notepy.gitlab.io | |
| */ | |
| /** | |
| * Function search for Boyer Moore Horspool algorithm | |
| * | |
| * @param string $needle pattern | |
| * @param string $haystack text | |
| * | |
| * @return int | |
| **/ | |
| function search($needle, $haystack) | |
| { | |
| $a = strlen($needle); | |
| $b = strlen($haystack); | |
| if ($a > $b) : | |
| return 0; | |
| endif; | |
| $skip = []; | |
| foreach(range(0, 256) as $c): | |
| $skip[] = $a; | |
| endforeach; | |
| foreach(range(0, $a - 1) as $c): | |
| $skip[ord($needle[$c])] = $a - $c - 1; | |
| endforeach; | |
| $c = $a - 1; | |
| while($c < $b): | |
| $d = $a - 1; | |
| $e = $c; | |
| while ($d >= 0 && $haystack[$e] == $needle[$d]): | |
| $d -= 1; | |
| $e -= 1; | |
| endwhile; | |
| if ($d == -1) : return $e + 1; | |
| endif; | |
| $c += $skip[ord($haystack[$c])]; | |
| endwhile; | |
| return 0; | |
| } | |
| //testing | |
| var_dump(search("test", "ini cuman test"), search("error", "ini cuman test")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment