如何从 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
How to remove all spaces from a string in PHP and Javascript
提问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);
Javascript:
Javascript:
var string = original_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);
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(' ', '');