在php中获取所有可能的子字符串 [英] Get all possible substring in php
问题描述
我正在尝试获取输入的所有子字符串的列表.对于 input=a,子串 {'','a'}对于 input=ab,子串 {'','a','b','ab','ba'}对于 input=abc,子串 {'','a','b','c','ab','bc','ca','ba','cb','ac','abc','acb','bac','bca','cab','cba'}等等.
I am trying to get a list of all substring of input. for input=a, substrings {'','a'} for input=ab, substrings {'','a','b','ab','ba'} for input=abc, substrings {'','a','b','c','ab','bc','ca','ba','cb','ac','abc','acb','bac','bca','cab','cba'} and so on.
我试过的代码在这里
function get_substr($string){
$array=str_split($string);
static $k=0;
for ($i=0; $i <count($array) ; $i++) {
for ($j=0; $j <count($array) ; $j++) {
$new_array[$k]=substr($string, $i, $j - $i + 1);
$k++;
}
}
return($new_array);
}
我有这个代码的 o/p 如下
and i have o/p of this code as below
请建议我需要进行哪些更改或任何其他想法来完成这项工作.
Please suggest me what changes I need or any alternative idea to do this work.
推荐答案
function find_posible_substr($input){
$input_len = strlen($input);
$possubstr = array();
$i = 0;
while($i < $input_len){
$j = 0;
while($j < $input_len){
$possubstr[] = substr($input, $j, $i + 1);
if(substr($input, $j, $i + 1) == $input){
break;
}
$j++;
}
$i++;
}
return $possubstr;
}
不知道你是否还在纠结这个问题.但无论如何我想分享我的.如果输入是abc
,则输出如下.
I don't know if you are still on this problem. But I want to share mine anyway.
If the input is abc
then the output will be as below.
Array
(
[0] => a
[1] => b
[2] => c
[3] => ab
[4] => bc
[5] => c
[6] => abc
)
这篇关于在php中获取所有可能的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!