PHP字符串排列 [英] php string permutation
问题描述
比方说,我有一个数组,这些数组由这些范围"a-zA-Z0-9"中的字符组成.我想做的是在4个字母的范围内获得所有可能的组合.字符串中可以重复字符.我正在寻找一种蛮力的方法.
这就是我认为迭代的方式:
"aaaa" "aaab" "aaac" ... "9999"
以蛮力方式:
$chars = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
$cnt = count($chars);
$strings = array();
for ($first = 0; $first < $cnt; $first++) {
for ($second = 0; $second < $cnt; $second++) {
for ($third= 0; $third< $cnt; $third++) {
for ($fourth= 0; $fourth < $cnt; $fourth++) {
$strings[] = $chars[$first] . $chars[$second] . $chars[$third] . $chars[$fourth];
}
}
}
}
您最终将得到一个honkin'大数组,因此您可能希望将一些数据库操作分散到一个循环中,因此$ strings不会太大,并且不会通过达到内存限制来杀死脚本. /p>
Let's say I have an array consisting of characters from these ranges "a-zA-Z0-9". What I want to do is get all possible combinations possible in a 4-letter range. Characters can be repeated in the string. I'm looking for a brute-force way to do it.
This is how I believe the iteration would be:
"aaaa" "aaab" "aaac" ... "9999"
In brute-force fashion:
$chars = array_merge(range('0', '9'), range('a', 'z'), range('A', 'Z'));
$cnt = count($chars);
$strings = array();
for ($first = 0; $first < $cnt; $first++) {
for ($second = 0; $second < $cnt; $second++) {
for ($third= 0; $third< $cnt; $third++) {
for ($fourth= 0; $fourth < $cnt; $fourth++) {
$strings[] = $chars[$first] . $chars[$second] . $chars[$third] . $chars[$fourth];
}
}
}
}
You'll end up with a honkin' big array, so you might want to sprinkle some database operations into one of the loops, so $strings doesn't get too big and kill your script by hitting a memory limit.
这篇关于PHP字符串排列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!