How to find all substrings of a string in PHP
php, string, substring
Solution
Using the in-php-array-is-the-duct-tape-of-the-universe way :P
function get_all_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;
}
$subs = get_all_substrings("a b c", " ");
print_r($subs);
Problem
I need to convert strings of the form ``` "a b c" ``` into arrays of the form ``` Array ( [0] => a [1] => a b [2] => a b c [3] => b [4] => b c [5] => c ) ``` Does PHP provide a native function for converting strings into all substrings? If not, what's the path of least resistance for getting all substrings? Is there a straightforward way to perhaps explode() the string, and use an array op to generate all [ordered] permutations? Cheers!