Ad space (banner)
๐Ÿ˜PHP Lessons
Lesson 32 / 68

Intro to Regular Expressions (Pattern Matching)

In this lesson you will learn the basics of regular expressions in PHP so you can validate and extract patterned strings such as email addresses and phone numbers. This is for anyone searching for "PHP preg_match how to use".

A regular expression is a special notation that describes the shape of a string. You can specify a pattern such as "three digits, a hyphen, then four digits", check whether text matches it, and pull out the matching part. PHP provides preg_match().

The sample code uses preg_match('/\d{3}-\d{4}-\d{4}/', $text, $matches) to extract the part matching a phone-number pattern into the $matches array. Notice that the match is available as $matches[0].

It looks like nothing but punctuation at first, but it is a powerful tool that pays off in practice, for example when validating email formats. A frequent beginner trip-up is the requirement to wrap the pattern in slashes - forget the '/pattern/' form and you get an error.

Learn regular expressions once and the skill transfers to most other programming languages. They are used widely in practice for form validation and log-file analysis alike.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run PHP directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)