我想做的是......我有一个名为 char 的数组和一个字符串$char = array("-","_","|","+","~");
$MyString = "this is test string";我想做的是用数组中的一个字符替换 $MyString 中的每个空格但我希望结果是这样的$MyString = "this is test string";$ExplodedString = explode(" ",$MyString);foreach ($char as $sinchar) { $text1 = preg_replace("/ /", $sinchar, $MyString ,1); foreach ($char as $sinchar) { $text2 = preg_replace("/ /", $sinchar, $text1 ,1); //echo $text2."\n"; foreach ($char as $sinchar) { $text3 = preg_replace("/ /", $sinchar, $text2 ,1); echo $text3."\n"; } }}这段代码对我来说工作得很好,但它是一个静态代码,我正在寻找更动态的东西,所以如果我添加一个具有更多空格的文本,我不必添加另一个循环。那么大家有什么解决办法吗?
1 回答
倚天杖
TA贡献1828条经验 获得超3个赞
您可以使用递归函数,将第一个单词的排列与其余单词的所有可能排列组合起来:
function computeAllPermutations(array $words, array $separators): array
{
switch (count($words)) {
case 0:
return [];
case 1:
return [$words[0]];
default:
$permutations = [];
foreach (computeAllPermutations(array_slice($words, 1), $separators) as $subPermutation) {
foreach ($separators as $separator) {
$permutations[] = $words[0] . $separator . $subPermutation;
}
}
return $permutations;
}
}
用法:
$words = preg_split('/\h+/', $MyString);
$permutations = computeAllPermutations($words, $char);
print_r($permutations);
- 1 回答
- 0 关注
- 90 浏览
添加回答
举报
0/150
提交
取消