All possible substrings in a String in PHP

By: Lukman Viewed: 153225 times  Printer Friendly Format    


The following code uses arrays to retrieve all possible substrings in a given string in PHP.

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);


Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial