How to Remove Spaces from String in PHP

How to remove spaces from string in PHP. In this tutorial i’ll explain how to remove spaces from string using regex as well as using in-built function in PHP.

If you know regex then it’s good otherwise you can refer my previous tutorial on Regular expression.

How to Remove Spaces from String in PHP

Let’s create a simple regex which remove whitespace from string.

Regex Symbols and their Meanings

\s = Matches any whitespace character (spaces, tabs, line breaks).
+ = Match one or more preceding token

 

How to Remove WhiteSpace from the Beginning of String in PHP

To remove spaces at the beginning of a string

^\s+ – Remove whitespace at the beginning of a string

^ – start at the beginning

How to sort string in PHP.

How to upload multiple files in PHP.

 

ltrim() – ltrim() strip whitespace or other characters from the beginning of string.

Syntax –

If you don’t specify second parameter, then it Strip whitespace from the beginning of a string.

 

How to Remove WhiteSpace from the End of String in PHP

METHOD 1 – Using Regex.

\s+$ – Remove whitespace at the end of a string

\s – Matches any whitespace character

+ – Match one or more preceding token

$ – Matches the end of a string

 

METHOD 2 – Using PHP in-built function rtrim().

rtrim() – Strip whitespace (or other characters) from the end of a string.

If you don’t specify second parameter, then it Strip whitespace from the end of a string.

 

How to Remove Multiple Spaces in String

\s{2,} – It will check for two or more consecutive spaces

regex_space

You can write, and test your regex pattern in regexr.

Let’s implement them in PHP function

 

Remove WhiteSpace from Beginning and End of String through trim() in PHP

PHP provides in-built trim() method through which you can strip whitespace from beginning and end of string.

trim(): Remove whitespaces at the beginning and end of a string.

 

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.