Bird
Raised Fist0
PHPprogramming~10 mins

Preg_match for pattern matching in PHP - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Preg_match for pattern matching
Start with input string
↓
Define regex pattern
↓
Call preg_match(pattern, string)
↓
Check if pattern matches string?
No→Return 0 (no match)
Yes↓
Return 1 (match found)
↓
Optionally fill matches array
↓
End
The program takes a string and a regex pattern, uses preg_match to check if the pattern matches the string, returns 1 if yes, 0 if no, and optionally stores matched parts.
Execution Sample
PHP
<?php
$pattern = '/cat/';
$string = 'The cat sat.';
if (preg_match($pattern, $string, $matches)) {
    echo "Match found: " . $matches[0];
} else {
    echo "No match.";
}
?>
This code checks if 'cat' is in the string and prints the matched word if found.
Execution Table
StepActionPatternStringpreg_match ResultMatches ArrayOutput
1Define pattern/cat/N/AN/AN/AN/A
2Define stringN/AThe cat sat.N/AN/AN/A
3Call preg_match/cat/The cat sat.1["cat"]N/A
4Check resultN/AN/A1 (true)N/AN/A
5Print matchN/AN/AN/AN/AMatch found: cat
💡 preg_match returns 1 because 'cat' is found in the string.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3Final
$patternundefined/cat//cat//cat//cat/
$stringundefinedundefinedThe cat sat.The cat sat.The cat sat.
$matchesundefinedundefinedundefined["cat"]["cat"]
Key Moments - 3 Insights
Why does preg_match return 1 instead of true or false?
preg_match returns 1 for a match, 0 for no match, and false on error. This is shown in execution_table row 3 where result is 1 meaning a match was found.
What is stored in the $matches array?
The $matches array stores the matched substring(s). In row 3, it contains ["cat"], the exact part of the string that matched the pattern.
What happens if the pattern is not found in the string?
preg_match returns 0 and $matches remains empty or unchanged. This is implied by the exit_note and would be shown if the string did not contain 'cat'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the value of $matches after step 3?
A[]
B["cat"]
Cnull
D["dog"]
💡 Hint
Check the 'Matches Array' column in row 3 of the execution_table.
At which step does preg_match confirm a match was found?
AStep 4
BStep 2
CStep 3
DStep 5
💡 Hint
Look at the 'preg_match Result' and 'Action' columns in the execution_table.
If the string was 'The dog sat.', what would preg_match return?
A0
Bfalse
C1
Dnull
💡 Hint
Refer to the exit_note and understand preg_match returns 0 when no match is found.
Concept Snapshot
preg_match(pattern, string, matches) checks if pattern matches string.
Returns 1 if match found, 0 if not, false on error.
Matches array stores matched parts.
Use /pattern/ syntax for regex.
Commonly used for simple pattern checks.
Full Transcript
This example shows how preg_match works in PHP. First, we define a regex pattern '/cat/'. Then we have a string 'The cat sat.'. Calling preg_match with these checks if 'cat' is inside the string. It returns 1 because it finds a match. The matched word 'cat' is stored in the matches array. If no match was found, preg_match would return 0. This helps us decide what to do next, like printing 'Match found: cat' or 'No match.'.

Practice

(1/5)
1. What does the PHP function preg_match return when the pattern is found in the string?
easy
A. 1
B. 0
C. true
D. false

Solution

  1. Step 1: Understand preg_match return values

    The function preg_match returns 1 if the pattern matches the string.
  2. Step 2: Differentiate from no match

    If the pattern is not found, it returns 0, not true or false.
  3. Final Answer:

    1 -> Option A
  4. Quick Check:

    preg_match returns 1 if pattern found [OK]
Hint: Remember: preg_match returns 1 for match, 0 for no match [OK]
Common Mistakes:
  • Confusing return values with boolean true/false
  • Assuming preg_match returns the matched string
  • Thinking preg_match returns number of matches
2. Which of the following is the correct syntax to check if the string $text contains the word "hello" using preg_match?
easy
A. preg_match('hello', $text);
B. preg_match('/hello/', $text);
C. preg_match(/hello/, $text);
D. preg_match("/hello", $text);

Solution

  1. Step 1: Identify correct pattern delimiters

    Patterns in preg_match must be enclosed in quotes and slashes, like '/pattern/'.
  2. 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.
  3. Final Answer:

    preg_match('/hello/', $text); -> Option B
  4. Quick Check:

    Pattern must be in quotes with slashes [OK]
Hint: Use quotes and slashes around pattern in preg_match [OK]
Common Mistakes:
  • Omitting quotes around the pattern
  • Omitting slashes around the pattern
  • Using wrong quote types inconsistently
3. What will be the output of the following PHP code?
$text = "apple123";
if (preg_match('/\d+/', $text)) {
echo "Digits found";
} else {
echo "No digits";
}
medium
A. Syntax error
B. No digits
C. Digits found
D. Empty output

Solution

  1. Step 1: Understand the pattern '/\d+/'

    The pattern \d+ matches one or more digits in the string.
  2. Step 2: Check if $text contains digits

    The string "apple123" contains digits "123", so preg_match returns 1 and the if condition is true.
  3. Final Answer:

    Digits found -> Option C
  4. Quick Check:

    Pattern \d+ matches digits, output is 'Digits found' [OK]
Hint: \d+ matches digits; check string for numbers [OK]
Common Mistakes:
  • Not escaping backslash properly in pattern
  • Assuming preg_match returns matched string
  • Confusing preg_match return with boolean true/false
4. The following code is intended to check if a string contains only letters. What is wrong with it?
$str = "Hello123";
if (preg_match('/^[a-zA-Z]+$/', $str)) {
echo "Only letters";
} else {
echo "Contains other characters";
}
medium
A. The pattern is correct but the string contains digits
B. Missing delimiters around the pattern
C. The pattern should use \w instead of [a-zA-Z]
D. preg_match should be preg_match_all

Solution

  1. 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.
  2. Step 2: Identify the actual problem

    The pattern is correct, but the string has digits, so the else branch runs.
  3. Final Answer:

    The pattern is correct but the string contains digits -> Option A
  4. Quick Check:

    Pattern matches only letters; digits cause no match [OK]
Hint: Check if string matches pattern exactly, not just pattern syntax [OK]
Common Mistakes:
  • Thinking pattern is wrong when string is the issue
  • Confusing preg_match with preg_match_all
  • Removing anchors ^ and $ incorrectly
5. You want to check if a string contains a valid email address using preg_match. Which pattern correctly matches a simple email format like 'user@example.com'?
hard
A. '/^[a-z]+@[a-z]+\.[a-z]{2,3}$/'
B. '/^[\d]+@[\d]+\.[\d]{2,4}$/'
C. '/\w+@\w+\.com/'
D. '/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/'

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    '/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/' -> Option D
  4. Quick Check:

    '/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,6}$/' matches common email format correctly [OK]
Hint: Use \w, dots, dashes, and domain length for email pattern [OK]
Common Mistakes:
  • Not using anchors ^ and $ to match whole string
  • Restricting domain or username too much
  • Ignoring dots and dashes in username or domain
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