如何在PHP中查找字符串的所有子字符串 [英] How to find all substrings of a string in PHP

查看:297
本文介绍了如何在PHP中查找字符串的所有子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要转换形式的字符串

I need to convert strings of the form

"a b c"

转换为以下形式的数组

Array
(
    [0] => a
    [1] => a b
    [2] => a b c
    [3] => b
    [4] => b c
    [5] => c
)

PHP是否提供了将字符串转换为所有子字符串的本机功能?如果不是,获取所有子字符串的阻力最小的途径是什么?有没有一种简单的方法也许可以explode()字符串,并使用数组op生成所有[有序]排列?

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?

干杯!

推荐答案

使用 in-php-array-is-the-duct-tape-of-universe 方式:P

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

这篇关于如何在PHP中查找字符串的所有子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆