How to replace whitespace with a single space

PHP: How to replace whitespace with a single space

If you want to replace multiple whitespace characters (multiple spaces, new lines, etc) with just a single space, use this:

  1. $code = preg_replace('!\s+!', ' ', $code);

webdevetc profile pic

I am a 29 year old backend web developer from London, mostly focusing on PHP and Laravel lately. This ( is my blog where I write about some web development topics (PHP, Laravel, Javascript, and some server stuff). contact me here.


Comments and discussion about How to replace whitespace with a single space

Found this interesting? Maybe you want to read some more in this series?

Or see other topics in the PHP language

Or see other languages/frameworks:
PHP Laravel Composer Apache CentOS and Linux Stuff WordPress General Webdev and Programming Stuff JavaScript
Or see random questions

How to replace values in a string, in JS

How to redirect your website to a new domain/location in .htaccess

How to block access to certain referrers in Apache using .htaccess

Set PHP config Variables (like ini_set) with .htaccess

What are Template literals (Template strings) in JS?

How to find the intersection (same values) from two arrays?

How to show (or log) all SQL queries executed by Laravel

How to autoload helper files with composer?

How to block multiple IP addresses in .htaccess

How to find the index of a value in an array in JS?