I need to convert strings of the form
\"a b c\"
into arrays of the form
Array
(
[0] => a
[1] => a b
[2] =
<?php
function get_all_substrings($input){
$subs = array();
$length = strlen($input);
for($i=0; $i<$length; $i++){
for($j=$i; $j<$length; $j++){
$subs[] = substr($input, $i, $j);
}
}
return $subs;
}
$subs = get_all_substrings("Hello world!");
print_r($subs);
?>
Even if there's a fancy two-liner to accomplish this, I doubt it's any more efficient or easy to understand (for anybody to understand it they'd probably have to look at the docs. Most folks probably get what substr does without even looking it up).
Substrings are not permutations. explode()
the string, then use two nested loops along with array_slice()
to get the relevant elements.
All possible substrings
<?php
$str1 = "ABCD";
$len = strlen($str1);
$arr = array();
for($i = 0; $i < $len; $i++){
for($j = 0; $j < $len - $i; $j++){
$arr [] = substr($str1,$i,($j+1));
}
}
echo(json_encode($arr));
?>