Skip to content

Instantly share code, notes, and snippets.

@chuehnone
Last active November 30, 2018 03:08
Show Gist options
  • Save chuehnone/a4d6bf36129cbecc7e4f3924acdeca8c to your computer and use it in GitHub Desktop.
Save chuehnone/a4d6bf36129cbecc7e4f3924acdeca8c to your computer and use it in GitHub Desktop.
PHP implement Boyer–Moore algorithm
<?php
/**
* @param string $text The string to search in.
* @param string $search The target string to search
*
* @return int The start index of the search string
*/
function getStringStartIndexByBoyerMoore($text, $search) {
$textLength = strlen($text);
$searchLength = strlen($search);
$table = getCharRightMinDistanceTable($search);
$index = $searchLength - 1;
while($index < $textLength) {
for ($i = $index, $j = $searchLength - 1 ; $text[$i] == $search[$j] ; $i--, $j--) {
if ($j == 0) {
return $i;
}
}
$index += isset($table[$text[$index]]) ? max($table[$text[$index]], 1) : $searchLength ;
}
return -1;
}
/**
* @param string $text
*
* @return array
*/
function getCharRightMinDistanceTable($text) {
$len = strlen($text);
$table = [];
for ($i = 0 ; $i < $len ; $i++) {
$table[$text[$i]] = $len - $i - 1;
}
return $table;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment