Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find all substrings of a string in PHP

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!

like image 336
Chris Tonkinson Avatar asked Jan 20 '10 07:01

Chris Tonkinson


1 Answers

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);
like image 197
Lukman Avatar answered Oct 10 '22 10:10

Lukman