Detecting forbidden characters in a string with PHP

Published on 2023-10-15 • Modified on 2023-10-15

This snippet shows how to detect forbidden characters in a string with PHP. Here is one of the many possible solutions using the strspn() function.


<?php

declare(strict_types=1);

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 Snippet280Trait
{
    public function snippet280(): void
    {
        $digits = '0123456789';
        $phones = [
            'valid' => '0320212223',
            'invalid' => 'O3 2O 2I 22 2E',
        ];

        foreach ($phones as $phone) {
            if (\strlen($phone) !== strspn($phone, $digits)) {
                echo sprintf('Illegal characters found in %s ❌, please retry! Allowed: %s', $phone, $digits).PHP_EOL;
            } else {
                echo sprintf('%s id valid. ✅', $phone).PHP_EOL;
            }
        }

        // That's it! 😁
    }
}

 Run this snippet  More on Stackoverflow   Read the doc  Random snippet

  Work with me!