ホームページ  >  記事  >  バックエンド開発  >  正規表現を使用して PHP テキストから空白行を効果的に削除する方法

正規表現を使用して PHP テキストから空白行を効果的に削除する方法

Barbara Streisand
Barbara Streisandオリジナル
2024-10-18 08:22:03243ブラウズ

How to Effectively Remove Blank Lines from PHP Text Using Regular Expressions?

How to Eliminate Blank Lines from PHP Text

You're attempting to remove blank lines (including whitespace lines) in PHP using regular expressions, but your current approach appears ineffective. Here's a solution to address your issue:

The following regular expression will remove blank lines, whether they contain whitespace or are completely empty:

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

Let's break down the elements of this regular expression:

  • Capturing Group (1): Matches blank lines or lines that start with carriage returns or line feeds.
  • Alternation 1: Matches zero or more carriage returns or line feeds.
  • Alternation 2: Matches one or more carriage returns or line feeds.
  • Quantifier ([\s\t]*): Matches zero or more whitespace characters (spaces or tabs).
  • Quantifier ([\r\n]+): Matches one or more carriage returns or line feeds.

This regular expression replaces the matched blank lines with a single newline character (\n). As a result, the output will remove all empty lines from your text, leaving only non-blank lines intact.

以上が正規表現を使用して PHP テキストから空白行を効果的に削除する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。