Skip to content

Instantly share code, notes, and snippets.

@michael34435
Created September 11, 2014 07:11
Show Gist options
  • Save michael34435/04dddce944868861e6dc to your computer and use it in GitHub Desktop.
Save michael34435/04dddce944868861e6dc to your computer and use it in GitHub Desktop.
modify from stackoverflow(I forgot where is it :/)
<?php
class Permute implements Iterator
{
private $base;
private $count;
private $current;
public function __construct($base)
{
$this->base = preg_split('/(?<!^)(?!$)/u', $base);
$this->count = count($this->base);
$this->current = reset($this->base);
}
public function current()
{
return $this->current;
}
public function key()
{
return null;
}
public function next()
{
for ($it = mb_strlen($this->current, "UTF-8") - 1; $it >= 0; $it--) {
$cur = preg_split('/(?<!^)(?!$)/u', $this->current);
$pos = array_search($cur[$it], $this->base);
if ($pos < ($this->count - 1)) {
$this->replace_index($this->current, $it, $this->base[$pos + 1]);
for ($i = $it + 1; $i < mb_strlen($this->current, "UTF-8"); $i++) {
$this->replace_index($this->current, $i, reset($this->base));
}
break ;
}
}
if ($it == -1) {
$this->current = str_repeat(reset($this->base), mb_strlen($this->current, "UTF-8") + 1);
}
}
public function rewind()
{
$this->current = reset($this->base);
}
public function valid()
{
return true;
}
private function replace_index(&$str, $index, $char)
{
$str = preg_split('/(?<!^)(?!$)/u', $str);
$new = "";
foreach ($str as $key => $value) {
if ($key == $index) {
$new .= $char;
} else {
$new .= $value;
}
}
$str = $new;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment