Probably the best thing to do is build up an iterative process for all the possibilities. In other words, something like this:
function findall($startString) {
// create an array of all strings that are distance one away
// each element would be $returnArray["abc"] = "abc";
}
$d = 2; // distance
$myArray[$startString] = $startString;
for($i = 0; $i < $d; $i++) {
$newCombos = array_merge(array(), $myArray);
foreach($myArray as $element) {
$newCombos = array_merge($newCombos, findall($element));
}
$myArray = array_merge(array(), $newCombos);
}
$myRegex = implode("|", $myArray);