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

Barbara Streisand
リリース: 2024-10-18 08:22:03
オリジナル
242 人が閲覧しました

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 サイトの他の関連記事を参照してください。

ソース:php
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!