所有可能的子串PHP
I use this function to get all the possible substrings of the $input="KRKRK". iT gives out some of the substrings , but doesn't take into consideration the first word of the string(i.e, K) into consideration while building up the substrings. What may be the problem?
function get_all_substrings($input)
{
$input = trim($input);
$subs = array();
$length = strlen($input);
for($i=1; $i<=$length; $i++)
{
$start = 0;
$sub_length = $i;
while(($start+$sub_length) <= $length)
{
$subs[] = substr($input, $start, $sub_length);
$start++;
}
}
return $subs;
}
Here's the Output array:
Array ( [0] => R [1] => K [2] => R [3] => K [4] => RK [5] => KR [6] => RK [7] => RKR [8] => KRK [9] => RKRK )
But why am I not getting the substrings K, KR, KRK, KRKR ??
我使用此函数获取$ input =“KRKRK”的所有可能子串。 iT发出 一些子串,但在构建子串时不考虑字符串的第一个字(即K)。 可能是什么问题? p>
function get_all_substrings($ input)
{
$ input = trim($ input);
$ subs = array(); \ n $ length = strlen($ input);
for($ i = 1; $ i&lt; = $ length; $ i ++)
{
$ start = 0;
$ sub_length = $ i;
\ n while(($ start + $ sub_length)&lt; = $ length)
{
$ subs [] = substr($ input,$ start,$ sub_length);
$ start ++;
}
}
返回$ subs;
}
code> pre>
这是输出数组: p>
数组([0] =&gt; R [1] =&gt; K [2] =&gt; R [3] =&gt; K [4] =&gt; RK [5] =&gt; KR [6] =&gt; RK [7] = &gt; RKR [8] =&gt; KRK [9] =&gt; RKRK)
code> pre>
但为什么我没有得到子串K,KR,KRK,KRKR ?? p>
div>
Here is what I whipped up -
function get_all_subs($input) {
$arr = str_split($input);
$all_subs = array();
for ($i = 0; $i < count($arr); $i++) {
for ($j = $i; $j < count($arr); $j++) {
$all_subs[] = implode('', array_slice($arr, $i, $j - $i + 1));
}
}
return $all_subs;
}
$input="KRKRK";
$substrings = get_all_subs($input);
print_r($substrings);
Here is a working example.
I honestly had no issues using the script when I ran it...
<?php
function get_all_substrings($input)
{
$input = trim($input);
$subs = array();
$length = strlen($input);
for($i=1; $i<=$length; $i++)
{
$start = 0;
$sub_length = $i;
while(($start+$sub_length) <= $length)
{
$subs[] = substr($input, $start, $sub_length);
$start++;
}
}
return $subs;
}
print_r(get_all_substrings("KRKRK"));
?>
This gave me the result:
Array ( [0] => K [1] => R [2] => K [3] => R [4] => K [5] => KR [6] => RK [7] => KR [8] => RK [9] => KRK [10] => RKR [11] => KRK [12] => KRKR [13] => RKRK [14] => KRKRK )
Try this! it will give the result as Array ( [0] => K [1] => KR [2] => KRK [3] => KRKR [4] => KRKRK )
$input="KRKRK";
function get_all_substrings($input)
{
for($i=0; $i<strlen($input); $i++){
$individual_char[] = $input[$i];
}
$temp_char = "";
for($i=0; $i<count($individual_char); $i++){
$final_array[] = $temp_char.$individual_char[$i];
$temp_char = $temp_char.$individual_char[$i];
}
return $final_array;
}
print_r(get_all_substrings($input));