[PHP] Convert a string into an array of characters

Published on 2019-12-05 • Modified on 2019-12-05

The str_split function is not well known. It converts a string into an array of characters (with the default second parameter). It is useful sometimes to avoid declaring an array manually like here with the str_replace function.


<?php declare(strict_types=1);

// src/Controller/Snippet/Snippet62Trait.php

namespace App\Controller\Snippet;

/**
 * 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 Snippet62Trait
{
    public function snippet62(): void
    {
        $tokenSize = 32;
        $random = random_bytes($tokenSize);
        $base = base64_encode($random);
        $clean = str_replace(str_split('+/-_'), '', $base);
        $cut = substr($clean, 0, $tokenSize);

        echo 'Token: '.$cut.PHP_EOL;
        echo 'Token length: '.\strlen($cut); // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Run on 3v4l.org  Random snippet