Padding Both Sides of a String

Learn how to add a padding character to both ends of a string up to a certain length.

We'll cover the following...

The padBoth helper method

In this lesson, we will look at the padBoth helper method, which adds a padding character to both ends of a string up to a certain length.

Press + to interact
<?php
/**
* Versions: Laravel 8, 9
*
* @return string
*/
public static function padBoth(
string $value,
int $length,
string $pad = ' '
);

The following examples demonstrate the basic usage of the padBoth helper method:

Press + to interact
<?php
use Illuminate\Support\Str;
// Returns "Hello"
Str::padBoth('Hello', 15);
// Returns "*****World*****"
Str::padBoth('World', 15, '*');

We can use the padBoth helper method to ...