Advertisement
Beginner PHP, Regular Expressions in PHP

What do common regular expression metacharacters like the dot, asterisk, and plus sign mean, and how are they used to build flexible matching patterns?

Short answer

The dot matches any single character except a newline, the asterisk means the preceding character or group can appear zero or more times, and the plus sign means the preceding character or group must appear one or more times, and combining these basic building blocks together…

Save PHP mock interview
Advertisement
AModel answer
The dot matches any single character except a newline, the asterisk means the preceding character or group can appear zero or more times, and the plus sign means the preceding character or group must appear one or more times, and combining these basic building blocks together, along with character classes and other metacharacters, lets you construct patterns that flexibly match a wide range of possible text variations rather than only a single exact string.
preg_match('/colou?r/', 'color');
preg_match('/colou?r/', 'colour');
// Both match, since the question mark makes the u optional
Real-world example
A text search feature uses a pattern with an optional character to correctly match both the American and British spelling of a word, accommodating both variations with a single flexible pattern rather than needing two separate checks.
Likely follow-ups
  • What is the difference between the asterisk and the plus sign quantifiers?
  • How do you match a literal dot character rather than having it match any character?
Related topics