Preg_split for splitting in PHP - Time & Space Complexity
We want to understand how the time it takes to split a string using preg_split changes as the string gets longer.
How does the work grow when the input string grows?
Analyze the time complexity of the following code snippet.
$string = "apple,banana,orange,grape";
$pattern = "/,/";
$result = preg_split($pattern, $string);
foreach ($result as $fruit) {
echo $fruit . "\n";
}
This code splits a string by commas into an array of fruits, then prints each fruit.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The preg_split function scans the entire string to find all commas and split accordingly.
- How many times: It processes each character in the string once to check for the pattern.
As the string gets longer, preg_split checks more characters to find split points.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows roughly in direct proportion to the string length.
Time Complexity: O(n)
This means the time to split grows linearly with the length of the input string.
[X] Wrong: "preg_split runs instantly no matter how long the string is."
[OK] Correct: The function must check each character to find split points, so longer strings take more time.
Understanding how string operations scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we changed the pattern to split by multiple characters or a more complex regex? How would the time complexity change?"