[PHP]如何去除字符串中的whitespace. - 拳不离手、曲不离口 - Speak with your code, my friend, not your word.
[C]ANSI C中有哪些预处理指令?
[PHP]如何给一个变量赋长字符串

[PHP]如何去除字符串中的whitespace.

clem posted @ 2009年8月12日 22:20 in Language with tags php , 2770 阅读

首先是whitespace的定义:任何在印刷术当中显示为空白的字符。包括以下:

Unicode记法

  • U+0009–U+000D (control characters, containing Tab, CR and LF)
  • U+0020 SPACE
  • U+0085 NEL (control character next line)
  • U+00A0 NBSP (NO-BREAK SPACE)
  • U+1680 OGHAM SPACE MARK
  • U+180E MONGOLIAN VOWEL SEPARATOR
  • U+2000–U+200A (different sorts of spaces)
  • U+2028 LS (LINE SEPARATOR)
  • U+2029 PS (PARAGRAPH SEPARATOR)
  • U+202F NNBSP (NARROW NO-BREAK SPACE)
  • U+205F MMSP (MEDIUM MATHEMATICAL SPACE)
  • U+3000 IDEOGRAPHIC SPACE

在php种,去除的方法主要有三种,这三种适用情况也不同。

1, trimStrip whitespace (or other characters) from the beginning and end of a string

trim()这个函数只会去除字符串开头结尾部分的部分whitespace,如下:

  • " " (ASCII 32 (0x20)), an ordinary space.
  • "\t" (ASCII 9 (0x09)), a tab.
  • "\n" (ASCII 10 (0x0A)), a new line (line feed).
  • "\r" (ASCII 13 (0x0D)), a carriage return.
  • "\0" (ASCII 0 (0x00)), the NUL-byte.
  • "\x0B" (ASCII 11 (0x0B)), a vertical tab.

但不会去除中间的whitespace,这一定要注意。

2, preg_replacePerform a regular expression search and replace

用正则表达式来去除whitespace,这个就可以比较彻底了,去除一个字符串中所有的whitespace。具体代码如下:

 

<?php
$str = 'foo      o';
$str = preg_replace('/\s/', '', $str);
// This will be 'fooo' now
echo $str;
?>

 3, str_replace(' ',”,$string);

 适合去除space,而非whitespace


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter