我想做的是..。
我有一个名为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";
}
}
}这段代码对我来说很好,但是它是静态代码,我正在寻找更动态的代码,所以如果我添加了一个有更多空格的文本,我就不必再添加一个循环了。
伙计们有什么解决办法吗?
发布于 2020-08-02 21:36:52
您可以使用递归函数,将第一个单词的排列与其余单词的所有可能的排列组合起来:
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);https://stackoverflow.com/questions/63220990
复制相似问题