Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove all spaces from a string in PHP and Javascript [duplicate]

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

How can I remove all spaces from a string in PHP and in Javascript? I want to remove all spaces from the left hand side, right hand side and from between each character.

For Example:

$myString = "  Hello   my     Dear  ";

I want to get this string as "HellomyDear".

Please demonstrate how I can do this in both PHP and Javascript.

like image 790
Saritha Avatar asked Apr 20 '11 10:04

Saritha


People also ask

How do you remove all the spaces from a string in JS?

JavaScript String trim() The trim() method removes whitespace from both sides of a string. The trim() method does not change the original string.

How do I trim a space in PHP?

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.

How do I remove spaces between words in a string?

We can use replace() to remove all the whitespaces from the string. This function will remove whitespaces between words too.


2 Answers

PHP

$newString = str_replace(" ","",$myString);

JavaScript

myString.replace(" ", "")
like image 155
Mild Fuzz Avatar answered Oct 25 '22 01:10

Mild Fuzz


Remove just spaces

PHP:

$string = str_replace(' ', '', $original_string);

str_replace() man page.

Javascript:

var string = original_string.replace(' ', '');

String.replace() man page.

Remove all whitespace

If you need to remove all whitespace from a string (including tabs etc) then you can use:

PHP:

$string = preg_replace('/\s/', '', $original_string);

preg_replace() man page.

Javascript:

var string = original_string.replace(/\s/g, '');
like image 32
Treffynnon Avatar answered Oct 25 '22 01:10

Treffynnon