php logo
PHP

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

/**

* 获取字符串按序全排列(英文) 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;

}


精品课程


guest

0 评论
内联反馈
查看所有评论