200-710 · Question #203
How many elements does the array $matches from the following code contain? $str = "The cat sat on the roof of their house."; $matches = preg_split("/(the)/i", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
The correct answer is D. 7. preg_split with PREG_SPLIT_DELIM_CAPTURE returns both the split parts and the captured delimiter matches. The pattern /(the)/i matches "the" case-insensitively three times in the string: "The" (start), "the" (in "the roof"), and "the" (in "their"). Three delimiters produce four…
Question
Options
- A2
- B3
- C4
- D7
- E9
How the community answered
(32 responses)- A6% (2)
- C3% (1)
- D81% (26)
- E9% (3)
Explanation
preg_split with PREG_SPLIT_DELIM_CAPTURE returns both the split parts and the captured delimiter matches. The pattern /(the)/i matches "the" case-insensitively three times in the string: "The" (start), "the" (in "the roof"), and "the" (in "their"). Three delimiters produce four surrounding parts ("", " cat sat on ", " roof of ", "ir house."), and inserting the three captured delimiters between them yields 7 elements total.
Why the distractors fail:
- C (4) is the most tempting wrong answer - it's the result without
PREG_SPLIT_DELIM_CAPTURE, where only the surrounding parts are returned (4 parts from 3 split points). - B (3) reflects only the count of "the" matches, ignoring what
preg_splitactually returns. - E (9) would require four delimiter matches, not three.
- A (2) has no reasonable basis in this context.
Memory tip: Think of PREG_SPLIT_DELIM_CAPTURE as "keep the scissors in the bag" - every time the string is cut, the cutter (captured group) gets tucked into the result array between the pieces. Formula: (n delimiters × 2) + 1 → here (3 × 2) + 1 = 7.
Topics
Community Discussion
No community discussion yet for this question.