PHP

PHP – How to strip all spaces out of a string in php

php-articles-memory
php-articles

PHP trim() or strip Function:

Definition and Usage:

The trim() function removes whitespace and other predefined characters from both sides of a string.

Related functions:

ltrim() – Removes whitespace or other predefined characters from the left side of a string

rtrim() – Removes whitespace or other predefined characters from the right side of a string

Syntax:

Php Code
trim(string,charlist)

sample php program with ltrim() function

Php Code
<?php
$data="how to remove blank spaces how";
$data1=ltrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>

Its output will be :

how to remove blank spaces how:<br> to remove blank spaces how:<br>

program with rtrim()

Php Code
<?php
$data="how to remove blank spaces how";
$data1=rtrim($data,"how");
echo $data.":<br>";
echo $data1.":<br>";
?>

Its output will be:

how to remove blank spaces how:<br>how to remove blank spaces :<br>

Here we can see that “how” is removed from end only, the beginning “how” remains in the ouput string .

We can use any of these function for remove the un necessary whitespaces or characters from the end or beginning or from both as per our requirement.And note trim() = rtrim() + ltrim() in action.

How to strip all spaces out of a string in php:

You have a string stored in a PHP variable, and you want to eliminate all whitespaces or spaces from that string with PHP, not only from the beginning or the end of the string.

Php Code
<?php
 
$firstString= 'this is just a string';
$newString = str_replace(' ', '', $firstString);
echo $newString; //outputs "thisisjustastring" as a string
 
?>

Solution for spaces:

Php Code
<?php
 
//You want to strip all spaces from the below string and obtain "thisisjustastring"
$firstString= 'this is just a string'; 
 
?>

Solution for whitespaces:

Php Code
<?php
 
$firstString= 'this is just a string';
$newString = preg_replace('/\s+/', '', $firstString);
echo $newString //outputs "thisisjustastring" as a string
 
?>

Difference between spaces and whitespaces:

Space is the regular space character between words, whitespace is any kind of space in text: regular space, new line, tab, etc.

READ  exec() vs system() vs passthru()

Their ASCII representation differs one from another, this is why we need different solutions for them.

About the author

Venkatesan Prabu

Venkatesan Prabu

Wikitechy Founder, Author, International Speaker, and Job Consultant. My role as the CEO of Wikitechy, I help businesses build their next generation digital platforms and help with their product innovation and growth strategy. I'm a frequent speaker at tech conferences and events.

1 Comment

Click here to post a comment