Laravel Tutorials

Repeat Strings Efficiently with Laravel's Str::repeat Method

Published
Repeat Strings Efficiently with Laravel's Str::repeat Method image

Laravel's Str::repeat method offers a simple solution for creating repeated string patterns by duplicating a string a specified number of times.

Repeat a string a specific number of times:

use Illuminate\Support\Str;

$character = 'x';
$repeated = Str::repeat($character, 4);
// Result: 'xxxx'

Here's how you might use it in a report formatter:

class ReportFormatter
{
    public function createSeparatorLine(int $length = 50)
    {
        return sprintf(
            '%s%s%s',
            '+',
            Str::repeat('-', $length - 2),
            '+'
        );
    }

    public function formatProgressBar(int $completed, int $total = 10)
    {
        $progress = Str::repeat('█', $completed);
        $remaining = Str::repeat('░', $total - $completed);
        
        return sprintf(
            '[%s%s] %d%%',
            $progress,
            $remaining,
            ($completed / $total) * 100
        );
    }

    public function createIndentation(int $level)
    {
        return sprintf(
            '%s%s',
            Str::repeat('  ', $level),
            '- '
        );
    }
}

$formatter = new ReportFormatter();

echo $formatter->createSeparatorLine(30);
// Output: +----------------------------+

echo $formatter->formatProgressBar(7);
// Output: [███████░░░] 70%

echo $formatter->createIndentation(3);
// Output:       - 

The repeat method provides a clean way to handle string repetition tasks in your Laravel applications.

Harris Raftopoulos photo

Senior Software Engineer • Staff & Educator @ Laravel News • Co-organizer @ Laravel Greece Meetup

Sponsored

acquaintsoft logo
Acquaint Softtech

Hire Laravel developers with AI expertise at $20/hr. Get started in 48 hours.

Visit Acquaint Softtech

The latest

View all →
Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures image

Laravel AI SDK 1.4 Lets Agents Recover From Tool Failures

Read article
Laravel Read Replicas: Check if a Replica Has Caught Up image

Laravel Read Replicas: Check if a Replica Has Caught Up

Read article
UUID Request Input and Migration Failure Events in Laravel 13.42 image

UUID Request Input and Migration Failure Events in Laravel 13.42

Read article
Replay Missed Laravel Scheduled Tasks With Schedule Catchup image

Replay Missed Laravel Scheduled Tasks With Schedule Catchup

Read article
Search Polymorphic Relations and Filament Tables With Laravel Searchable image

Search Polymorphic Relations and Filament Tables With Laravel Searchable

Read article
Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs image

Laravel Rest Api 3.0: Typed Fields, Metrics, and OpenAPI Docs

Read article