Skip to content

Instantly share code, notes, and snippets.

@joshuaadickerson
Created July 19, 2013 06:38
Show Gist options
  • Select an option

  • Save joshuaadickerson/6037124 to your computer and use it in GitHub Desktop.

Select an option

Save joshuaadickerson/6037124 to your computer and use it in GitHub Desktop.
<?php
$app['random_string'] = $app->protect(function (array $options = array()) {
static $default_options = array(
'length' => 5,
'uppercase' => true,
'lowercase' => true,
'numeric' => true,
'special_chars' => false,
'chars' => 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
);
if (!empty($options))
{
$options = array_merge($default_options, $options);
if ((bool) $options['uppercase'])
$options['chars'] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
if ((bool) $options['lowercase'])
$options['chars'] .= 'abcdefghijklmnopqrstuvwxyz';
if ((bool) $options['numeric'])
$options['chars'] .= '0123456789';
if (!empty($options['special_chars']))
$options['chars'] .= $options['special_chars'];
if (!empty($options['remove_chars']))
$options['chars'] = str_replace($options['remove_chars'], '', $options['chars']);
if (isset($options['min_length']) && isset($options['max_length']))
$options['length'] = (int) mt_rand($options['min_length'], $options['max_length']);
$options['length'] = (int) $options['length'];
}
else
{
$options = $default_options;
}
$string = '';
$char_len = strlen($options['chars']) - 1;
for ($i = 0; $i < $options['length']; $i++)
$string .= $options['chars'][mt_rand(0, $char_len)];
return $string;
});
var_dump($this->app['random_string'](array('length' => 10)));
// error
// Fatal error: Function name must be a string in [the following line]
// var_dump($this->app['random_string'](array('length' => 10)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment