如何在PHP中查找字符串的所有子字符串

Chr*_*son 5 php string substring

我需要转换表单的字符串

"a b c"
Run Code Online (Sandbox Code Playgroud)

到表格的数组

Array
(
    [0] => a
    [1] => a b
    [2] => a b c
    [3] => b
    [4] => b c
    [5] => c
)
Run Code Online (Sandbox Code Playgroud)

PHP是否提供将字符串转换为所有子字符串的本机函数?如果没有,那么获得所有子串的阻力最小的路径是什么?是否有一种直接的方法可能爆炸()字符串,并使用数组操作生成所有[有序]排列?

干杯!

Luk*_*man 13

使用in-php-array-is-the-duct-of-the-universe方式: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);
Run Code Online (Sandbox Code Playgroud)


ech*_*cho 7

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

?>
Run Code Online (Sandbox Code Playgroud)

即使有一个花哨的双线来完成这个,我怀疑它更有效或更容易理解(任何人理解它他们可能不得不看看文档.大多数人可能得到什么substr做甚至没有看它向上).