javascript 有谁知道如何从字符串中删除十六进制 A0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13221691/
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
Does anyone know how I can get rid of hex A0 from a string?
提问by
I have the following string:
我有以下字符串:
Hello. ? Hello.
你好。? 你好。
If you look at the string in a hex editor it looks like this:
如果您在十六进制编辑器中查看字符串,它看起来像这样:
48 65 6C 6C 6F 2E 20 A0 20 20 48 65 6C 6C 6F 2E
48 65 6C 6C 6F 2E 20 A0 20 20 48 65 6C 6C 6F 2E
Note the A0
in the middle. (This is the no-break space character).
注意A0
中间的。(这是不间断空格字符)。
A0
is breaking some JavaScript I am using so I would like to remove it when the string is being pre-processed by a PHP script.
A0
正在破坏我正在使用的一些 JavaScript,所以我想在 PHP 脚本对字符串进行预处理时将其删除。
If I use the following code:
如果我使用以下代码:
$text = preg_replace("/\xA0/"," ", $text);
the A0
gets replaced with 00
which is also a troublesome character.
As you can see from the preg_replace
function, it should be replace by a space, or 20
.
将A0
被替换为00
这也是个麻烦人物。
从preg_replace
函数中可以看出,它应该被替换为空格或20
。
Do any of you know how I can get rid of this troublesome A0
character?
你们有谁知道我怎样才能摆脱这个麻烦的A0
角色吗?
Thank you.
谢谢你。
EDIT: I am using Windows-1252 and cannot switch to UTF-8. This won't be a problem if you are using UTF-8...
编辑:我使用的是 Windows-1252,无法切换到 UTF-8。如果您使用的是 UTF-8,这将不是问题...
采纳答案by Baba
I figured out a solution:
我想出了一个解决方案:
First convert the encoding type, and then do the replace:
首先转换编码类型,然后进行替换:
$text = mb_convert_encoding($text, "Windows-1252", "UTF-8");
$text = preg_replace("/\xA0/"," ", $text);
回答by Baba
Simple
简单的
$string = str_replace(chr(160), " ", $string);
Simple Test
简单测试
$string = "48656C6C6F2E20A0202048656C6C6F2E" ;
^----------------------- 0A
//Rebuild String
$string = pack("H*",$string);
//Replace 0A Charater
$string = str_replace(chr(160), " ", $string);
//Send Output
var_dump($string,bin2hex($string));
Output
输出
string 'Hello. Hello.' (length=16)
string '48656c6c6f2e2020202048656c6c6f2e' (length=32)
^---------------------- 0A Replaced with 02