Generating a random string with the Symfony string component

Published on 2021-11-21 • Modified on 2021-11-21

In this snippet, we see how to generate a random string with the Symfony string component. There is this static function fromRandom in the ByteString class. The first argument is the length of the string to generate, and the second one allows to restrict the characters to use by specifying an alphabet. Note that you can use the php range() function to get all letters from a to z without typing everything. Also, note that the default alphabet excludes zeros (0) to avoid confusion with the O letter.


<?php

declare(strict_types=1);

namespace App\Controller\Snippet;

use Symfony\Component\String\ByteString;

/**
 * I am using a PHP trait to isolate each snippet in a file.
 * This code should be called from a Symfony controller extending AbstractController (as of Symfony 4.2)
 * or Symfony\Bundle\FrameworkBundle\Controller\Controller (Symfony <= 4.1).
 * Services are injected in the main controller constructor.
 */
trait Snippet175Trait
{
    public function snippet175(): void
    {
        echo ByteString::fromRandom(32)->toString(); // default alphabet is [1-9][A-Z][a-z] (e.g: new random password)
        echo "\n";
        echo ByteString::fromRandom(8, implode('', range('A', 'Z')))->toString(); // uppercase letters only (e.g: sponsor code)
        echo "\n";
        echo ByteString::fromRandom(4, '0123456789')->toString(); // numbers only (e.g: pin code)

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  More on the web  Random snippet

  Work with me!