获取中英文字符串按序全排列

2019-12-06  本文已影响0人  晨雨微风

/**

* 获取字符串按序全排列(英文) e.g. abcd => a ab abc abcd b bc bcd c cd d

*

* @param $str

* @param string $separator

* @return array

*/

function getSortCombinations($str, $separator = '') {

    if ($separator !== '') {

        $chars = explode($separator, $str);

    } else {

        $chars = str_split($str);

    }

    $res = $chars;

    $count = count($chars);

    for ($i = 0; $i < $count - 1; $i++) {

        $tmp = $chars[$i];

        for ($j = $i + 1; $j < $count; $j++) {

            $tmp = $tmp . $chars[$j];

            $res[] = $tmp;

        }

}

    return $res;

}

/**

* 获取字符串按序全排列(中文)

*

* @param $str

* @return array

*/

function getSortCombinationsChinese($str) {

    $chars = preg_split('/(?<!^)(?!$)/u', $str);

    $res = $chars;

    $count = count($chars);

    for ($i = 0; $i < $count - 1; $i++) {

        $tmp = $chars[$i];

        for ($j = $i + 1; $j < $count; $j++) {

            $tmp = $tmp . $chars[$j];

            $res[] = $tmp;

        }

}

    return $res;

}

推荐: 浮生无事的博客

上一篇 下一篇

猜你喜欢

热点阅读