Ваш код заменяет каждый экземпляр символа в строке, поэтому он не может действительно работать.
Моя реализация:
$searchterm = $_POST['searchterm'];
$search = array( array('e', '3'), array('t', '7'), array('e', 'E') );
function replace($string, $prefix = '')
{
global $search;
// If $string is empty, we've reached the last character,
// so there is only one permutation. In that case, return it.
if(!$string) return array($prefix);
// Otherwise, take the first character in a string,
// then prepend it to all found combinations of the rest.
$result = array();
$letter = substr($string, 0, 1); // <- first character (head of $string)
$rest = substr($string,1); // <- next characters (tail of $string)
// Find all combinations of $rest (with $prefix and $letter
// prepended to them), then add them to the $result array.
$result = array_merge($result, replace($rest, $prefix . $letter));
foreach($search as $term) {
// In case the current $letter can be substituted by something in
// $search, repeat the last step with the replaced character
// instead of $letter.
if($term[0] == $letter) {
$result = array_merge($result, replace($rest, $prefix . $term[1]));
}
}
return $result;
}
var_dump(replace($searchterm));
Поскольку функция должна возвращать все комбинации,он рекурсивно называет себя как для исходного, так и для каждого замененного символа.
Теперь, почему он вообще работает?Для каждого вызова один символ перемещается из префикса $ string в $.Этот символ является первым символом строки $ или его замещенным значением.Если есть замещенные значения, результаты возвращаются как для исходного, так и для модифицированного.Когда больше нет символов для перемещения, он возвращает префикс $, который теперь содержит всю строку.
Итак, для строки 'pet' дерево вызовов будет выглядеть так:
[$string, $prefix]
->['', 'pe7']
|
['pet', '']->['et', 'p']->['t', 'pe']->['', 'pet']
|
->['t', 'p3']->['', 'p3t']
|
->['', 'p37']
И из этого вы можете ясно увидеть комбинации: «pe7», «pet», «p3t», «p37» (хотя порядок будет другим, но это не важно).