用PHP正则表达式清除字符串的连续空白 (php 正则 只保留一个空格)

PHP方法:

<?php
$str = " This line containstliberal rn use of whitespace.nn";
 
// First remove the leading/trailing whitespace
//去掉開始和結束的空白
$str = trim($str);
 
// Now remove any doubled-up whitespace
//去掉跟隨別的擠在一塊的空白
$str = preg_replace('/s(?=s)/', '', $str);
 
// Finally, replace any non-space whitespace, with a space
//最後,去掉非space 的空白,用一個空格代替
$str = preg_replace('/[nrt]/', ' ', $str);
 
// Echo out: 'This line contains liberal use of whitespace.'
echo " {$str}";
?>

原文:http://blog.xuite.net/coke750101/networkprogramming/31431168-%E5%8E%BB%E9%99%A4%E5%AD%97%E4%B8%B2%E4%B8%AD%E9%96%93%E7%9A%84%E9%80%A3%E7%BA%8C%E7%A9%BA%E7%99%BD

jquery方法:

jQuery.trim( str )

以下是与jQuery.trim()函数相关的jQuery示例代码,以演示jQuery.trim()函数的具体用法:

//在当前页面内追加换行标签和指定的HTML内容
function w( html ){
    document.body.innerHTML += "<br/>" + html;
}

// 输出两侧添加双引号,以便于区分字符串边界
w( '"' + $.trim( "   CodePlayer   " ) + '"'); // "CodePlayer"
// 只会去除两端的连续空白字符
w( '"' + $.trim( "   Code Player   " ) + '"'); // "Code Player"
w( '"' + $.trim( "rnt   CodePlayer   t" ) + '"'); // "CodePlayer"


w( '"' + $.trim( "" ) + '"'); // ""
w( '"' + $.trim( 12 ) + '"'); // "12"
w( '"' + $.trim( null ) + '"'); // ""
w( '"' + $.trim( undefined ) + '"'); // ""
w( '"' + $.trim( new Object() ) + '"'); // "[object Object]"

原文:http://www.365mini.com/page/jquery_trim.htm