0
0
PHPprogramming~20 mins

Preg_split for splitting in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Preg_split Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
?>
AArray ( [0] => apple,banana,orange )
BArray ( [0] => apple [1] => banana [2] => orange [3] => )
CArray ( [0] => apple [1] => banana,orange )
DArray ( [0] => apple [1] => banana [2] => orange )
Attempts:
2 left
💡 Hint
preg_split splits the string where the pattern matches, returning all parts as array elements.
Predict Output
intermediate
2: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);
?>
AArray ( [0] => one [1] => two [2] => three,four )
BArray ( [0] => one [1] => two [2] => three [3] => four )
CArray ( [0] => one,two,three [1] => four )
DArray ( [0] => one [1] => two [2] => three [3] => four [4] => )
Attempts:
2 left
💡 Hint
The limit parameter controls how many pieces the string is split into.
Predict Output
advanced
2: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);
?>
AArray ( [0] => [1] => apple [2] => [3] => banana [4] => orange [5] => )
BArray ( [0] => apple [1] => banana [2] => orange )
CArray ( [0] => apple [1] => [2] => banana [3] => orange )
DArray ( [0] => apple,banana,orange )
Attempts:
2 left
💡 Hint
The PREG_SPLIT_NO_EMPTY flag removes empty strings from the result.
Predict Output
advanced
2: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);
?>
AArray ( [0] => red [1] => 1 [2] => green [3] => 2 [4] => blue [5] => 3 )
BArray ( [0] => red1green2blue3 )
CArray ( [0] => red [1] => green [2] => blue )
DArray ( [0] => red [1] => 1green2blue3 )
Attempts:
2 left
💡 Hint
PREG_SPLIT_DELIM_CAPTURE includes the parts matched by parentheses in the output.
🧠 Conceptual
expert
3: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);
?>
A7
B8
C4
D1
Attempts:
2 left
💡 Hint
The regex uses a lookbehind to split after each digit.