0
0
PHPprogramming~5 mins

Preg_split for splitting in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the preg_split function do in PHP?

preg_split splits a string into pieces using a regular expression as the separator.

Click to reveal answer
beginner
How do you use preg_split to split a string by commas and spaces?

Use a pattern like /[ ,]+/ to split by one or more commas or spaces.

Example: preg_split('/[ ,]+/', 'apple, banana orange') splits into ['apple', 'banana', 'orange'].

Click to reveal answer
intermediate
What is the difference between explode and preg_split?

explode splits a string by a fixed string separator.

preg_split splits by a pattern, allowing more flexible splitting like multiple separators or patterns.

Click to reveal answer
intermediate
What does the PREG_SPLIT_NO_EMPTY flag do in preg_split?

This flag removes empty strings from the result array after splitting.

It helps avoid empty pieces when separators are next to each other.

Click to reveal answer
beginner
Write a simple PHP code snippet using preg_split to split a sentence by spaces.
<?php
$sentence = 'Hello world from PHP';
$words = preg_split('/\s+/', $sentence);
print_r($words);
?>

This splits the sentence into words by one or more spaces.

Click to reveal answer
What kind of argument does preg_split use to split a string?
AA regular expression pattern
BA fixed string separator
CAn integer index
DA callback function
Which flag removes empty strings from the result of preg_split?
APREG_SPLIT_DELIM_CAPTURE
BPREG_SPLIT_OFFSET_CAPTURE
CPREG_SPLIT_NO_EMPTY
DPREG_SPLIT_REMOVE_EMPTY
What will preg_split('/,/', 'a,b,,c') return without flags?
A['a', 'b', '', 'c']
B['a', 'b', 'c']
C['a,b,,c']
D['a', '', 'b', 'c']
Which function is simpler but less flexible than preg_split for splitting strings?
Aimplode
Bstr_replace
Csubstr
Dexplode
What does the pattern /\s+/ match in preg_split?
AOne or more letters
BOne or more whitespace characters
COne or more digits
DOne or more commas
Explain how preg_split works and when you would use it instead of explode.
Think about splitting by spaces and commas together.
You got /3 concepts.
    Describe the purpose of the PREG_SPLIT_NO_EMPTY flag and give an example scenario.
    Imagine splitting 'a,,b' by comma.
    You got /3 concepts.