Hi Couchers,

Recently, I needed a random string generator for strings shorter than what Couch's <cms:random_name /> provides.

So I made my own tag with some optional parameters: length and characters; maybe they'll come in handy down the road :) Default length is 42, and characters are alphanumeric.

- - - - - - -

Examples:

Code: Select all

<cms:random_string length='15' />
q4spjImfcesk6Jh

<cms:random_string length='8' characters='abcd5678' />
c8778dc7

<cms:random_string length='6' characters='123456789' />
824592



- - - - - - -

To install, put the following in your couch/addons/kfunctions.php file:

Code: Select all


$FUNCS
->register_tag('random_string', function($params, $node){
    global $FUNCS;

    extract($FUNCS->get_named_vars(
        array(
            'length' => '',
            'characters' => ''
        ),
        $params)
    );
    
    if 
(!strlen($length)) {$length = 42;}
    if (!strlen($characters)) {$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';}

  $charactersLength = strlen($characters);
  $result = '';
  for ($i = 0; $i < $length; $i++) {
    $result .= $characters[rand(0, $charactersLength - 1)];
  }
  return $result;
});