PHP正则表达式A与D修饰符使用求助:测试无差异问题
Hey there! I totally get the frustration—regex modifiers can feel invisible when you can't see their impact right away. Let's break down PHP's A and D modifiers with concrete examples that'll make their purpose click.
A (PCRE_ANCHORED) Modifier This modifier forces your regex pattern to only match starting at the very first character of the input string. Think of it like an implicit ^ anchor at the start of your pattern—but it’s not redundant in every case.
When it makes a clear difference
Suppose you have a string with multiple instances of your target pattern:
$string = "apple banana apple cherry"; $pattern = "/apple/"; // Without the A modifier: finds ALL matches preg_match_all($pattern, $string, $matches); print_r($matches[0]); // Output: Array ( [0] => apple [1] => apple ) // With the A modifier: only matches the FIRST occurrence (at position 0) preg_match_all($pattern . "A", $string, $matches); print_r($matches[0]); // Output: Array ( [0] => apple )
Why your test might have seemed identical
If your pattern already included a ^ anchor, or if your test string only had one possible match starting at the beginning, adding A won’t change the result. The modifier only reveals its effect when there are potential matches later in the string that you want to exclude.
D (PCRE_DOLLAR_ENDONLY) Modifier This changes how the $ anchor behaves: by default, $ matches either the absolute end of the string or the position just before a trailing newline (\n). The D modifier restricts $ to only match the absolute end of the string.
When it makes a clear difference
Test with a string that ends in a newline:
$string_with_newline = "orange\n"; $pattern = "/orange$/"; // Without D: matches successfully (since $ hits before the trailing newline) if (preg_match($pattern, $string_with_newline)) { echo "Matched without D!\n"; // This runs } // With D: no match (now $ only hits after the newline) if (preg_match($pattern . "D", $string_with_newline)) { echo "Matched with D!\n"; } else { echo "No match with D!\n"; // This runs } // For a string without a trailing newline, both behave the same $string_no_newline = "orange"; preg_match($pattern, $string_no_newline); // Matches preg_match($pattern . "D", $string_no_newline); // Also matches
- For
A: It restricts all matches (not just the first one) to start at position 0—even withpreg_match_all, you’ll never get matches from later in the string. - For
D: It only affects the$anchor. If you’re using\z(which always matches the absolute end of the string),Dwon’t change anything.
内容的提问来源于stack exchange,提问作者DrZorg

