/D (Dollar End Only)
What is /D (Dollar End Only)?
/D (Dollar End Only): Makes $ match only at the very end of the string, never right before a trailing newline (which is $'s default PCRE behaviour). In PCRE, $ normally matches at the end of the string, and also just before a newline at the very end. So /^\d+$/ accepts "123\n". The D modifier in PHP removes that exception, so $ only matches at the true end.
Frequently asked questions about /D (Dollar End Only)
How is /D (Dollar End Only) used in practice?
This matters for validation. A value that ends in a newline can slip through a check, then cause trouble later, for example in a header, a file name or a log line. Using /^\d+$/D closes that gap.
What should you keep in mind with /D (Dollar End Only)?
An easier option that works in most regex engines is \z, which always means the absolute end of the string. /^\d+\z/ reads clearly and does not depend on a PHP-specific flag. Whichever you choose, add a test case with a trailing newline, because this bug never shows up with the input you type by hand.
At a glance
| Category | Regex flags |
|---|---|
| Explained by | Reinier de la Parra |
| Updated |