Home >Backend Development >PHP Tutorial >How Can I Match Newline Characters in PHP Regex Without Using [\\r\\n]?

How Can I Match Newline Characters in PHP Regex Without Using [\\r\\n]?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 19:00:04658browse

How Can I Match Newline Characters in PHP Regex Without Using [\r\n]?

Matching Newline Characters in PHP Regex without [rn]

In PHP, the regular expression [rn] is commonly used to match carriage returns (r) or linefeeds (n). However, what if you want to match these characters without using this specific pattern?

Unicode Newline Escape Sequence: R

PCRE introduces the R escape sequence, which by default matches Unicode newline sequences. These include:

  • rn (CRLF)
  • n (LF)
  • r (CR)
  • f (Form feed)
  • x0b (Vertical tab)
  • x85 (Next line)

Example:

<code class="php">$string = "
Test
";

if (preg_match('~\R~', $string)) {
  echo "Matched";
} else {
  echo "Not Matched";
}</code>

Unicode Newline Escape Sequence with 'u' Flag:

To match newline characters outside the ASCII range, enable the 'u' (unicode) flag:

<code class="php">preg_match('~\R~u', $string);</code>

Restricting R to CR, LF, or CRLF:

If you only want to match carriage returns, linefeeds, or both, use the following pattern:

<code class="php">preg_match('~(*BSR_ANYCRLF)\R~', $string);</code>

Additional Conventions for Newline Characters:

PCRE also supports various conventions for indicating newline characters:

  • (*CR) - Carriage return
  • (*LF) - Linefeed
  • (*CRLF) - Carriage return, followed by linefeed
  • (*ANYCRLF) - Any of the above three
  • (*ANY) - All Unicode newline sequences

Note: R does not have special meaning inside a character class and instead acts as the literal character "R."

The above is the detailed content of How Can I Match Newline Characters in PHP Regex Without Using [\\r\\n]?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn