How to Remove All Spaces Out of a String in PHP?

PHP

Nicesnippets

66

21-11-2020


Hi Guys,

In this example,I will learn you how to remove all spaces out of a string in php.you can easy and simply remove all spaces out of a string in php.

Example 1: str_replace() Method


The str_replace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str.

Syntax:

str_replace($searchVal, $replaceVal, $subjectVal, $count)

<?php

// PHP program to remove all white

// spaces from a string

// Declare a string

$str = " Nice Snippests ";

// Using str_replace() function

// to removes all whitespaces

$str = str_replace(' ', '', $str);

// Printing the result

echo $str;

?>

Output:

NiceSnippests

Example 2: str_ireplace() Method

The str_ireplace() method is used to replace all the occurrences of the search string (” “) by replacing string (“”) in the given string str. The difference between str_replace and str_ireplace is that str_ireplace is a case-insensitive.

Syntax:

str_ireplace($searchVal, $replaceVal, $subjectVal, $count)

<?php

// PHP program to remove all

// white spaces from a string

$str = " Nice Snippests ";

// Using str_ireplace() function

// to remove all whitespaces

$str = str_ireplace (' ', '', $str);

// Printing the result

echo $str;

?>

Output:

NiceSnippests

Example 3: preg_replace() Method

The preg_replace() method is used to perform a regular expression for search and replace the content.

Syntax:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

<?php

// PHP program to remove all

// white spaces from a string

$str = " Nice Snippests ";

// Using preg_replace() function

// to remove all whitespaces

$str = preg_replace('/\s+/', '', $str);

// Printing the result

echo $str;

?>

Output:

NiceSnippests

It will help you...