Q:

How to Strip All Spaces Out of a String in PHP

0

How to Strip All Spaces Out of a String in PHP

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the PHP str_replace() Function

You can simply use the PHP str_replace() function to strip or remove all spaces inside a string.

Let's take a look at the following example to see how it actually works:

<?php
$str = 'This is a simple piece of text.';
$new_str = str_replace(' ', '', $str);
echo $new_str; // Outputs: Thisisasimplepieceoftext.
?>

The above example will however only remove spaces. If you want to remove all whitespaces including tabs, newlines, etc. you can use the preg_replace() function which perform a regular expression search and replace, as demonstrated in the following example:

<?php
$str = "This is a simple \npiece\tof text.";
$new_str = preg_replace("/\s+/", "", $str);
echo $new_str; // Outputs: Thisisasimplepieceoftext.
?>

In the above example \t represents the tab character, whereas \n represents the newline character.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

PHP  and MySQL Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Get the Current Year using PHP... >>
<< How to Make a Redirect in PHP...