提供幾個php替換分行符號的方法

來源:互聯網
上載者:User
  1. ?$str="this is a test \n";
  2. $patten = array("\r\n", "\n", "\r");
  3. ?//先替換掉\r\n,然後是否存在\n,最後替換\r
  4. $str=str_replace($order, "", $str);
  5. ?>
複製代碼
  1. //php 有三種方法來解決

  2. //1、使用str_replace 來替換換行
  3. $str = str_replace(array("\r\n", "\r", "\n"), "", $str);

  4. //2、使用正則替換

  5. $str = preg_replace('//s*/', '', $str);

  6. //3、使用php定義好的變數 (建議使用)

  7. $str = str_replace(PHP_EOL, '', $str);
複製代碼
  1. /*
  2. * 獲得使用者作業系統的分行符號,\n
  3. * @access public
  4. * @return string
  5. */
  6. function get_crlf()
  7. {
  8. if (stristr($_SERVER['HTTP_USER_AGENT'], 'Win'))
  9. {
  10. $the_crlf = '\r\n';
  11. }
  12. elseif (stristr($_SERVER['HTTP_USER_AGENT'], 'Mac'))
  13. {
  14. $the_crlf = '\r'; // for old MAC OS
  15. }
  16. else
  17. {
  18. $the_crlf = '\n';//權重大一點
  19. }
  20. return $the_crlf;
  21. }
複製代碼

注意:在前台頁面顯示的時候,用nl2br使換行變成

第二種執行個體說明:

發現一個有趣的事情:

  1. $text="aaaa

  2. ccc";

  3. $text=str_replace('\n‘,"",$text);

  4. $text=str_replace('\r‘,"",$text);
  5. $text=str_replace('\r\n‘,"",$text);

複製代碼

正常來說,上面的代碼應該可以替換分行符號了,但是事實上並非如此。很鬱悶,試了很多次,就是不起作用。最後改成這樣:

  1. $text=str_replace("\n","",$text);
  2. $text=str_replace("\r","",$text);
  3. $text=str_replace("\r\n","",$text);
複製代碼

居然就可以了,原來是雙引號,單引號的問題!

雙引號比單引號效率差點,因為雙引號在被php解析的過程中 ,還會判斷裡面會不會有變數,單引號就不會有這個判斷,故而一般來講,沒涉及到變數的情況下,我都會用單引號,沒想到這次替換分行符號,用單引號居然不行·····

最後寫成:

  1. $order = array("\r\n", "\n", "\r");
  2. $replace = '';
  3. $text=str_replace($order, $replace, $text);
複製代碼

這樣便可以替換分行符號了。是不是很方便呢。

>>> 您可能感興趣的文章:php去除字串分行符號執行個體解析php壓縮html(清除分行符號,清除定位字元,去掉注釋標記)php表單中轉換textarea分行符號的方法php正則過濾html標籤、空格、分行符號等的程式碼範例php去除分行符號的方法小結php壓縮html網頁代碼(清除空格、分行符號、定位字元、注釋標記等)的方法php產生excel與控制Excel儲存格中的分行符號

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.