首頁 > 後端開發 > php教程 > 如何在 PHP 中使用正規表示式有效刪除空白行?

如何在 PHP 中使用正規表示式有效刪除空白行?

Susan Sarandon
發布: 2024-10-18 08:22:29
原創
578 人瀏覽過

How to Remove Blank Lines Effectively in PHP Using Regular Expressions?

Removing Blank Lines in PHP

You've encountered a challenge in removing blank lines from PHP text using regular expressions. The regular expressions you attempted have not yielded the desired results, leaving you with unwanted white space in the output.

To effectively remove blank lines, you can utilize the following regular expression:

<code class="php">preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $string);</code>
登入後複製

This regular expression thoroughly analyzes the text:

  • 1st Capturing Group:

    • ^[\r\n]* - Matches lines starting with white space or empty lines.
    • [\r\n]+ - Matches consecutive new line characters.
  • [\s\t]*: Matches any white space (spaces or tabs).
  • [\r\n]+: Matches consecutive new line characters again.

By using this regular expression, you can condense multiple blank lines, white space-only lines, or a combination of both into a single new line character. This gives you the desired result of removing all blank lines from your PHP text.

以上是如何在 PHP 中使用正規表示式有效刪除空白行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板