Bird
Raised Fist0
PHPprogramming~10 mins

Preg_split for splitting in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Preg_split for splitting
Input string
↓
Define regex pattern
↓
Call preg_split with pattern and string
↓
Regex matches delimiters
↓
Split string at matches
↓
Return array of substrings
The preg_split function takes a string and a regex pattern, finds matches for the pattern, and splits the string at those matches, returning an array of parts.
Execution Sample
PHP
<?php
$input = "apple,banana;cherry orange";
$pattern = "/[ ,;]+/";
$result = preg_split($pattern, $input);
print_r($result);
?>
This code splits the input string by commas, semicolons, or spaces using preg_split and prints the resulting array.
Execution Table
StepActionRegex MatchResulting Array
1Start with input stringN/A["apple,banana;cherry orange"]
2Define regex pattern /[ ,;]+/N/A["apple,banana;cherry orange"]
3Call preg_split with pattern and inputMatches commas, semicolons, spaces["apple", "banana", "cherry", "orange"]
4Print resulting arrayN/A["apple", "banana", "cherry", "orange"]
💡 All delimiters matched and string split into 4 parts
Variable Tracker
VariableStartAfter preg_splitFinal
$input"apple,banana;cherry orange""apple,banana;cherry orange""apple,banana;cherry orange"
$patternundefined"/[ ,;]+/""/[ ,;]+/"
$resultundefined["apple", "banana", "cherry", "orange"]["apple", "banana", "cherry", "orange"]
Key Moments - 2 Insights
Why does preg_split split at commas, semicolons, and spaces all at once?
Because the regex pattern /[ ,;]+/ matches one or more of any of these characters, so preg_split uses all of them as delimiters (see execution_table step 3).
What happens if the input string starts or ends with a delimiter?
preg_split will create empty strings at the start or end of the array unless you use the PREG_SPLIT_NO_EMPTY flag (not shown here). This is why trimming delimiters matters.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what does preg_split return?
A["apple,banana;cherry orange"]
B["apple", "banana", "cherry", "orange"]
C["apple", "banana;cherry orange"]
D["apple banana cherry orange"]
💡 Hint
Check the 'Resulting Array' column at step 3 in the execution_table.
At which step does preg_split actually split the string?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look for when the array changes from one string to multiple parts in the execution_table.
If the pattern was changed to "/[,]+/", what would be the result array?
A["apple", "banana;cherry orange"]
B["apple", "banana", "cherry", "orange"]
C["apple,banana;cherry orange"]
D["apple banana cherry orange"]
💡 Hint
Changing the pattern to only commas means only commas split the string, so semicolons and spaces remain inside parts.
Concept Snapshot
preg_split(pattern, string) splits a string by regex matches.
Pattern defines delimiters.
Returns array of substrings.
Multiple delimiters can be combined in pattern.
Use flags to control empty parts.
Full Transcript
This visual trace shows how preg_split works in PHP. We start with an input string containing words separated by commas, semicolons, and spaces. We define a regex pattern that matches any of these delimiters. When preg_split is called, it finds all matches of the pattern and splits the string at those points, returning an array of the separated words. The execution table shows each step, including the initial string, pattern definition, splitting action, and final output. The variable tracker follows the values of input, pattern, and result variables. Key moments clarify why multiple delimiters work together and what happens with delimiters at string edges. The quiz tests understanding of the splitting step, output array, and effect of changing the pattern. The snapshot summarizes the main points about preg_split usage.

Practice

(1/5)
1. What does the PHP function preg_split do?
easy
A. Counts the number of words in a string.
B. Joins array elements into a string.
C. Replaces parts of a string matching a pattern.
D. Splits a string into parts using a regular expression pattern.

Solution

  1. Step 1: Understand the function purpose

    preg_split is designed to split strings based on patterns, not fixed characters.
  2. Step 2: Compare options with function behavior

    Only Splits a string into parts using a regular expression pattern. describes splitting using a regular expression pattern, which matches preg_split functionality.
  3. Final Answer:

    Splits a string into parts using a regular expression pattern. -> Option D
  4. Quick Check:

    preg_split splits string by regex pattern = A [OK]
Hint: Remember: preg_split uses regex to split strings [OK]
Common Mistakes:
  • Confusing preg_split with implode or join functions
  • Thinking preg_split replaces text instead of splitting
  • Assuming preg_split counts words
2. Which of the following is the correct syntax to split a string by commas using preg_split?
easy
A. preg_split('/,/', $string);
B. preg_split(',', $string);
C. preg_split($string, '/,/');
D. preg_split($string, ',');

Solution

  1. Step 1: Identify correct parameter order

    The first parameter of preg_split is the regex pattern as a string, the second is the input string.
  2. Step 2: Check regex pattern format

    The pattern must be enclosed in delimiters like slashes /, /. preg_split('/,/', $string); uses this correctly.
  3. Final Answer:

    preg_split('/,/', $string); -> Option A
  4. Quick Check:

    Pattern first with slashes, then string = B [OK]
Hint: Pattern goes first with slashes, then the string [OK]
Common Mistakes:
  • Omitting regex delimiters like slashes
  • Swapping the order of parameters
  • Using plain string instead of regex pattern
3. What is the output of the following PHP code?
$text = "apple,banana;orange|grape";
$result = preg_split('/[,;|]/', $text);
print_r($result);
medium
A. ["apple,banana;orange|grape"]
B. ["apple", "banana;orange|grape"]
C. ["apple", "banana", "orange", "grape"]
D. ["apple", "banana", "orange|grape"]

Solution

  1. Step 1: Understand the regex pattern

    The pattern /[,;|]/ matches any comma, semicolon, or pipe character as separators.
  2. Step 2: Split the string by these separators

    The string splits at each comma, semicolon, and pipe, resulting in four parts: "apple", "banana", "orange", "grape".
  3. Final Answer:

    ["apple", "banana", "orange", "grape"] -> Option C
  4. Quick Check:

    Split by , ; | = ["apple", "banana", "orange", "grape"] [OK]
Hint: Regex with multiple separators splits into all parts [OK]
Common Mistakes:
  • Not recognizing all separators in regex
  • Expecting only comma to split
  • Confusing output format with string instead of array
4. The following code is intended to split a string by spaces, but it causes an error. What is the problem?
$str = "one two three";
$parts = preg_split(' ', $str);
print_r($parts);
medium
A. The print_r function is used incorrectly.
B. The pattern is missing regex delimiters.
C. preg_split cannot split by spaces.
D. The string variable is empty.

Solution

  1. Step 1: Check the pattern parameter

    The pattern passed is a plain space character without regex delimiters, which is invalid syntax for preg_split.
  2. Step 2: Correct pattern format

    Regex patterns must be enclosed in delimiters like slashes, e.g., '/ /' to match a space.
  3. Final Answer:

    The pattern is missing regex delimiters. -> Option B
  4. Quick Check:

    Regex pattern needs delimiters like slashes [OK]
Hint: Always wrap regex pattern in delimiters like slashes [OK]
Common Mistakes:
  • Using plain string without delimiters as pattern
  • Assuming preg_split works like explode for spaces
  • Blaming print_r for output issues
5. You want to split a string by any number of spaces or commas, but ignore empty parts in the result. Which preg_split call achieves this?
hard
A. preg_split('/[ ,]+/', $string, -1, PREG_SPLIT_NO_EMPTY);
B. preg_split('/[ ,]/', $string);
C. preg_split('/[ ,]+/', $string);
D. preg_split('/[ ,]+/', $string, 0);

Solution

  1. Step 1: Understand the pattern and flags

    The pattern /[ ,]+/ matches one or more spaces or commas, so it splits on any group of these separators.
  2. Step 2: Use flag to remove empty parts

    The flag PREG_SPLIT_NO_EMPTY tells preg_split to exclude empty strings from the result array.
  3. Step 3: Check other options

    preg_split('/[ ,]/', $string); splits on single separators but may leave empty parts. preg_split('/[ ,]+/', $string); does not remove empty parts. preg_split('/[ ,]+/', $string, 0); uses 0 as limit which is invalid.
  4. Final Answer:

    preg_split('/[ ,]+/', $string, -1, PREG_SPLIT_NO_EMPTY); -> Option A
  5. Quick Check:

    Use + for multiple separators and NO_EMPTY flag [OK]
Hint: Use + in pattern and PREG_SPLIT_NO_EMPTY flag [OK]
Common Mistakes:
  • Not using + to match multiple separators
  • Forgetting PREG_SPLIT_NO_EMPTY to remove blanks
  • Using invalid limit parameter
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard