function isInDict($word, $dict) {
foreach ($dict as $entry) {
if ($entry === $word) {
return true;
}
}
return false;
}
function wordBreak($str, $strsize, $result, $dict) {
for ($i = 1; $i <= $strsize; $i++) {
$subStr = substr($str, 0, $i);
if (isInDict($subStr, $dict)) {
if ($i == $strsize) {
echo $result . $subStr . PHP_EOL;
return;
}
wordBreak(substr($str, $i), $strsize - $i, $result . $subStr . " ", $dict);
}
}
}
$str = "butterflyplaybasketballwithbags";
$dict = ["butterfly", "basketball", "bagpiper", "and", "play",
"with", "butter", "fly", "basket", "ball", "bags"];
wordBreak($str, strlen($str), "", $dict);
/*
run:
butter fly play basket ball with bags
butter fly play basketball with bags
butterfly play basket ball with bags
butterfly play basketball with bags
*/