Padding a multibyte string with PHP
Published on 2024-09-21 • Modified on 2024-09-21
This snippet shows how to pad a multibyte string with PHP. This function was introduced in PHP 8.3. I don't have concrete use cases in mind, but we know it exists 🙂. Note that is doesn't work with Unicode symbols encoded with 8 bytes like flags 🇬🇧.
<?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 Snippet320Trait
{
public function snippet320(): void
{
var_dump(mb_str_pad('🙂😊', 7, '🤓😎', STR_PAD_RIGHT));
var_dump(mb_str_pad('🙂😊', 7, '🤓😎', STR_PAD_BOTH));
var_dump(mb_str_pad('🎉', 3, '🙂', STR_PAD_LEFT));
// That's it! 😁
}
}
Run this snippet More on Stackoverflow Read the doc Random snippet
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
