The main purpose of regular expressions is to perform advanced pattern matching on text strings. A pattern defines rules so that a computer can recognize a sequence of characters.
Let's take for example, a pattern which matches a 7-digit phone number.
$test = '867-5309'; $pattern = '|^[0-9]{3}-[0-9]{4}$|'; $isphone = preg_match($pattern, $test); echo 'result = ' . $isphone;
A pattern like this may seem daunting at first if you are new to regular expressions. Let's break down the individual components and see how this pattern works.
[0-9], what we mean is any character between 0 and 9 (meaning any digit.)
So the pattern we have made will only match a 7-digit phone number with a hyphen between the first 3 digits and the last 4 digits. The pattern [0-9] is such a common pattern, that there exists a special notation to define this (\d). You could also do away with the brace notation and just repeat this sequence the required number of times like:
$pattern = '|^\d\d\d-\d\d\d\d$|';
For simple patterns, this type of pattern is much simpler to understand. We leave it up to you to decide which is best for your purposes.