PHP清除字串中空白Regex

來源:互聯網
上載者:User

先利用trim系列函數來刪除左右空格

 代碼如下 複製代碼


<?php

trim 去除一個字串兩端空格,
rtrim 是去除一個字串右部空格,
ltrim 是去除一個字串左部空格。

echo trim(" 空格 ")."<br>";
echo rtrim(" 空格 ")."<br>";
echo ltrim(" 空格 ")."<br>";

?>

刪除所有空格不能使用php trim()函數,因類他也只能是去除兩邊空閑

 代碼如下 複製代碼


function trimall($str)//刪除空格
{
 $qian=array(" "," ","t","n","r");
         $hou=array("","","","","");
 return str_replace($qian,$hou,$str); 
}

上面只能刪除是一些常見的空格了,下面分享一個更具體的。

 代碼如下 複製代碼

$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 "<pre>{$str}</pre>";


中間就是利用了替換連續空格與左右空格之後再利用preg_replace替換去除重複的,然後再用另一個Regex[nrt]來尋找任何殘餘的分行符號(n), 斷行符號(r), 或定位字元(t) 即可。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.