6

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.

Community
  • 1
  • 1
Saritha
  • 1,947
  • 5
  • 18
  • 24
  • @eisberg: Please click on "flag" -> "it doesn't belong here" -> "exact duplicate". – NikiC Apr 20 '11 at 10:53
  • 1
    Not duplicate of that question now it has been edited (although, I would wager it is still a duplicate of another) – Mild Fuzz Apr 20 '11 at 11:08

4 Answers4

17

PHP

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

JavaScript

myString.replace(" ", "")
Mild Fuzz
  • 29,463
  • 31
  • 100
  • 148
7

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, '');
Treffynnon
  • 21,365
  • 6
  • 65
  • 98
0

use the str_replace function:

str_replace(' ','',$myString)
bicccio
  • 384
  • 1
  • 19
0

PHP:

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

Javascript:

mystring = mystring.replace(' ', '');
Sander Marechal
  • 22,978
  • 13
  • 65
  • 96