Preg_match for pattern matching in PHP - Time & Space Complexity
When using preg_match in PHP, it's important to know how the time it takes grows as the input string gets longer.
We want to understand how the pattern matching works scales with input size.
Analyze the time complexity of the following code snippet.
$string = "Hello, this is a sample text.";
$pattern = '/sample/';
if (preg_match($pattern, $string)) {
echo "Match found!";
} else {
echo "No match.";
}
This code checks if the word "sample" appears anywhere in the given string.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The pattern matcher scans through the input string character by character.
- How many times: Up to once per character in the string, depending on the pattern and input.
The time to check the pattern grows roughly in proportion to the length of the input string.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: As the string gets longer, the work grows roughly in a straight line with the input size.
Time Complexity: O(n)
This means the time to find a match grows linearly with the length of the input string.
[X] Wrong: "preg_match always runs instantly no matter the input size."
[OK] Correct: The function must check characters one by one, so longer strings take more time.
Understanding how pattern matching scales helps you write efficient code and explain your choices clearly in interviews.
"What if the pattern uses complex wildcards or backreferences? How would the time complexity change?"
Practice
preg_match return when the pattern is found in the string?Solution
Step 1: Understand preg_match return values
The functionpreg_matchreturns 1 if the pattern matches the string.Step 2: Differentiate from no match
If the pattern is not found, it returns 0, not true or false.Final Answer:
1 -> Option AQuick Check:
preg_match returns 1 if pattern found [OK]
- Confusing return values with boolean true/false
- Assuming preg_match returns the matched string
- Thinking preg_match returns number of matches
$text contains the word "hello" using preg_match?Solution
Step 1: Identify correct pattern delimiters
Patterns inpreg_matchmust be enclosed in quotes and slashes, like '/pattern/'.Step 2: Check each option's syntax
preg_match('/hello/', $text); uses quotes and slashes correctly. preg_match('hello', $text); misses slashes. preg_match(/hello/, $text); misses quotes. preg_match("/hello", $text); misses closing slash.Final Answer:
preg_match('/hello/', $text); -> Option BQuick Check:
Pattern must be in quotes with slashes [OK]
- Omitting quotes around the pattern
- Omitting slashes around the pattern
- Using wrong quote types inconsistently
$text = "apple123";
if (preg_match('/\d+/', $text)) {
echo "Digits found";
} else {
echo "No digits";
}
Solution
Step 1: Understand the pattern '/\d+/'
The pattern\d+matches one or more digits in the string.Step 2: Check if $text contains digits
The string "apple123" contains digits "123", sopreg_matchreturns 1 and the if condition is true.Final Answer:
Digits found -> Option CQuick Check:
Pattern \d+ matches digits, output is 'Digits found' [OK]
- Not escaping backslash properly in pattern
- Assuming preg_match returns matched string
- Confusing preg_match return with boolean true/false
$str = "Hello123";
if (preg_match('/^[a-zA-Z]+$/', $str)) {
echo "Only letters";
} else {
echo "Contains other characters";
}
Solution
Step 1: Analyze the pattern and string
The pattern '/^[a-zA-Z]+$/' matches strings with only letters from start to end. The string "Hello123" contains digits, so it does not match.Step 2: Identify the actual problem
The pattern is correct, but the string has digits, so the else branch runs.Final Answer:
The pattern is correct but the string contains digits -> Option AQuick Check:
Pattern matches only letters; digits cause no match [OK]
- Thinking pattern is wrong when string is the issue
- Confusing preg_match with preg_match_all
- Removing anchors ^ and $ incorrectly
preg_match. Which pattern correctly matches a simple email format like 'user@example.com'?Solution
Step 1: Understand email pattern requirements
A simple email has letters, digits, dots, or dashes before and after '@', then a dot and 2-6 letter domain.Step 2: Evaluate each pattern
'/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/' matches letters, digits, dots, dashes before and after '@', and domain with 2-6 letters. '/^[a-z]+@[a-z]+\.[a-z]{2,3}$/' is too restrictive (only lowercase letters, domain 2-3 letters). '/\w+@\w+\.com/' matches only '.com' domains and misses anchors. '/^[\d]+@[\d]+\.[\d]{2,4}$/' matches digits only, which is invalid for emails.Final Answer:
'/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/' -> Option DQuick Check:
'/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/' matches common email format correctly [OK]
- Not using anchors ^ and $ to match whole string
- Restricting domain or username too much
- Ignoring dots and dashes in username or domain
Ready to prove it?
Pass the test and this pattern moves unknown
