Home >Backend Development >PHP Tutorial >How Can I Match Newline Characters in PHP Regex Without Using [\\r\\n]?
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:
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:
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!