Ben Borgers

How to remove double spaces in a string in Laravel

January 30, 2021

Here’s how you can use Laravel’s Str helper to remove double spaces from a string in PHP, using regex:

use Illuminate\Support\Str;

$string = 'Here is my sentence.  There are  double spaces.';

$newString = Str::of($string)->replaceMatches('/ {2,}/', ' ');

This takes any part of the string that matches {2,} (a space character occurring two or more times in a row) and replaces it with a single space.

Subscribe to my newsletter!

A weekly round-up of new blog posts and updates to projects I’m working on.