Of the two, the uniqid one is my choice. However, why would you want to generate a string of only hexadecimal characters (0-9a-f) and why assign the value to a variable only to return it?
$generator = new CompositeStringGenerator();
$generator->addGenerator(
new SpecialCharacterStringGenerator()
)->addGenerator(
new NumericStringGenerator()
)->addGenerator(
new LowerCaseAlphabeticStringGenerator()
)->addGenerator(
new UpperCaseAlphabeticStringGenerator()
);
echo $generator->generate(10);
interface StringGeneratorInterface
{
public function generate($length);
}
abstract class StringGenerator
{
protected
$character_pool;
public function __construct($character_pool){
$this->character_pool = (string)$character_pool;
}
public function generate($length){
if(0 === strlen($this->character_pool)){
throw new LogicException('Character pool is empty');
}
$string = '';
while($length > strlen($string)){
$string .= substr(
str_shuffle(
$this->character_pool
),
0,
1
);
}
return $string;
}
}
class CompositeStringGenerator implements StringGeneratorInterface
{
protected
$generators = array();
public function addGenerator(StringGeneratorInterface $generator){
array_push($this->generators, $generator);
return $this;
}
public function generate($length){
$string = '';
while($length > strlen($string)){
shuffle($this->generators);
foreach($this->generators as $generator){
if($length <= strlen($string)){
break;
}
$string .= $generator->generate(1);
}
}
return str_shuffle($string);
}
}
class SpecialCharacterStringGenerator extends StringGenerator implements StringGeneratorInterface
{
public function __construct(){
parent::__construct('!"£$%^&*()_+=-{}][~#@;:?<>,.');
}
}
class NumericStringGenerator extends StringGenerator implements StringGeneratorInterface
{
public function __construct(){
parent::__construct('0123456789');
}
}
class LowerCaseAlphabeticStringGenerator extends StringGenerator implements StringGeneratorInterface
{
public function __construct(){
parent::__construct(implode('', range('a', 'z')));
}
}
class UpperCaseAlphabeticStringGenerator extends StringGenerator implements StringGeneratorInterface
{
public function __construct(){
parent::__construct(implode('', range('A', 'Z')));
}
}