开发者

PHP function to loop thru a string and replace characters for all possible combinations

开发者 https://www.devze.com 2023-03-07 13:46 出处:网络
I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.

I am trying to write a function that will replace characters in a string with their HTML entity encoded equivalent.

I want it to be able to go through all the possible combinations for the given string, for example:

  • go one-by-one
  • then combo i.e.. 2 at a time, then three at a time, till you get length at a time
  • then start in combo split, i.e.. first and last, then first and second to last
  • then first and last two, fist and second/third last

So for the characters "abcd" it would return:

a开发者_如何学运维bcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd
abcd

etc.......... so on and so forth till there are no other combinations

Any ideas, or has anyone seen a function somewhere I could modify for this purpose?


loop from 0 to 2^length - 1. On each step, if Nth bit of the loop counter is 1, encode the Nth character

$str = 'abcd';

$len = strlen($str);

for($i = 0; $i < 1 << $len; $i++) {
    $p = '';
    for($j = 0; $j < $len; $j++)
        $p .= ($i & 1 << $j) ? '&#' . ord($str[$j]) . ';' : $str[$j];
    echo $p, "\n";
}


There are 2^n combinations, so this will get huge fast. This solution will only work as long as it fits into PHP's integer size. But really who cares? A string that big will print so many results you'll spend your entire life looking at them.

<?php
$input = 'abcd';

$len = strlen($input);
$stop = pow(2, $len);

for ($i = 0; $i < $stop; ++$i)
{
  for ($m = 1, $j = 0; $j < $len; ++$j, $m <<= 1)
  {
    echo ($i & $m) ? '&#'.ord($input[$j]).';' : $input[$j];
  }
  echo "\n";
}


How about this?

<?php
function permutations($str, $n = 0, $prefix = "") {
   if ($n == strlen($str)) {
      echo "$prefix\n";
      return;
   }

   permutations($str, $n + 1, $prefix . $str[$n]);
   permutations($str, $n + 1, $prefix . '&#' . ord($str[$n]) . ';');
}

permutations("abcd");
?>
0

精彩评论

暂无评论...
验证码 换一张
取 消