用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}";
?>

 

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://justcode.ikeepstudying.com/2015/04/%E7%94%A8php%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B8%85%E9%99%A4%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E8%BF%9E%E7%BB%AD%E7%A9%BA%E7%99%BD/

Loading

Add a Comment

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.