How to Remove White Space from a String in PHP

PHP has build function  trim()  to remove the white space from a given string.

trim() function will remove whitespace including non-breaking spaces, newlines, and tabs from the beginning and end of the string. It will not remove whitespace occurs in the middle of the string


$my_str = '    Welcome to PHP Programing  ';
echo strlen($my_str); // Outputs: 31
$trimmed_str = trim($my_str);
echo strlen($trimmed_str); // Outputs: 25



How to check string has whitespace or not in php?

To check whether a string has no whitespace, use the preg_match() in PHP


Let's check example


This will return output like below

The name (PHP Laravel Framework) has the space