Question & Answer: Need help desgining a function in php that takes letters such as def and gives each possible substring. Then writes those substrings to a file……

Need help desgining a function in php that takes letters such as def and gives each possible substring. Then writes those substrings to a file.

Ex:

d

e

f

de

ef

def

Expert Answer

 

In order to print each possible substring the best way is to explode the string and then use and array operation to generate all possible combinations in a sequenced way. Here is one possible way to do it:

<?php
function substrings($input, $delim = ”) {
$arr = explode($delim, $input);
$out = array();
for ($i = 0; $i < count($arr); $i++) {
for ($j = $i; $j < count($arr); $j++) {
$out[] = implode($delim, array_slice($arr, $i, $j – $i + 1));
}
}
return $out;
}

$string = substrings(“d e f”, ” “);
print_r($string);
?>

The above program will generate all the possible substring of the the given string and to save them to a file just execute the following command.

file_put_contents(‘filename.txt’, print_r($arrayname,true));

This will put the contents of the array subs to the specified filename.

Still stressed from student homework?
Get quality assistance from academic writers!