如何从 PHP 和 Javascript 中的字符串中删除所有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5729028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:36:48  来源:igfitidea点击:

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

phpjavascriptstring

提问by Saritha

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

可能的重复:
如何从 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.

如何从 PHP 和 Javascript 中的字符串中删除所有空格?我想从左侧,右侧和每个字符之间删除所有空格。

For Example:

例如:

$myString = "  Hello   my     Dear  ";

I want to get this string as "HellomyDear".

我想将此字符串作为“HellomyDear”。

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

请演示我如何在 PHP 和 Javascript 中执行此操作。

回答by Mild Fuzz

PHP

PHP

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

JavaScript

JavaScript

myString.replace(" ", "")

回答by Treffynnon

Remove just spaces

只删除空格

PHP:

PHP:

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

str_replace()man page.

str_replace()手册页

Javascript:

Javascript:

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

String.replace()man page.

String.replace()手册页

Remove all whitespace

删除所有空格

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

如果您需要从字符串中删除所有空格(包括制表符等),则可以使用:

PHP:

PHP:

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

preg_replace()man page.

preg_replace()手册页

Javascript:

Javascript:

var string = original_string.replace(/\s/g, '');

回答by bicccio

use the str_replace function:

使用 str_replace 函数:

str_replace(' ','',$myString)

回答by Sander Marechal

PHP:

PHP:

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

Javascript:

Javascript:

mystring = mystring.replace(' ', '');