Challenge - 5 Problems
Preg_split Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of preg_split with simple delimiter
What is the output of the following PHP code?
PHP
<?php $input = "apple,banana,orange"; $result = preg_split('/,/', $input); print_r($result); ?>
Attempts:
2 left
💡 Hint
preg_split splits the string where the pattern matches, returning all parts as array elements.
✗ Incorrect
The pattern '/,/' matches commas, so preg_split splits the string at each comma, producing an array of the fruits.
❓ Predict Output
intermediate2:00remaining
preg_split with limit parameter
What is the output of this PHP code?
PHP
<?php $input = "one,two,three,four"; $result = preg_split('/,/', $input, 3); print_r($result); ?>
Attempts:
2 left
💡 Hint
The limit parameter controls how many pieces the string is split into.
✗ Incorrect
With limit=3, preg_split splits into at most 3 parts. The last part contains the rest of the string after the second comma.
❓ Predict Output
advanced2:00remaining
preg_split with PREG_SPLIT_NO_EMPTY flag
What is the output of this PHP code?
PHP
<?php $input = ",apple,,banana,orange,"; $result = preg_split('/,/', $input, -1, PREG_SPLIT_NO_EMPTY); print_r($result); ?>
Attempts:
2 left
💡 Hint
The PREG_SPLIT_NO_EMPTY flag removes empty strings from the result.
✗ Incorrect
The input has empty parts between commas. Using PREG_SPLIT_NO_EMPTY removes those empty strings from the output array.
❓ Predict Output
advanced2:00remaining
preg_split with capturing parentheses
What is the output of this PHP code?
PHP
<?php $input = "red1green2blue3"; $result = preg_split('/(\d)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE); print_r($result); ?>
Attempts:
2 left
💡 Hint
PREG_SPLIT_DELIM_CAPTURE includes the parts matched by parentheses in the output.
✗ Incorrect
The pattern captures digits. With PREG_SPLIT_DELIM_CAPTURE, the digits appear as separate elements in the output array.
🧠 Conceptual
expert3:00remaining
Understanding preg_split behavior with complex regex
Given the code below, how many elements will the resulting array have?
PHP
<?php $input = "a1b2c3d4"; $result = preg_split('/(?<=\d)/', $input); echo count($result); ?>
Attempts:
2 left
💡 Hint
The regex uses a lookbehind to split after each digit.
✗ Incorrect
The pattern splits the string after each digit, resulting in 4 parts: 'a1', 'b2', 'c3', 'd4'.