PHP preg_match_all() Tutorial 🎯

beginner
23 min

PHP preg_match_all() Tutorial 🎯

Welcome to this comprehensive guide on using the preg_match_all() function in PHP! This powerful tool is a must-know for any PHP developer and we're excited to help you master it. Let's dive right in! πŸ“

What is preg_match_all()?

preg_match_all() is a PHP function that allows you to search for multiple matches within a subject string using regular expressions (regex). It's an extension of the preg_match() function, which finds only the first match.

Why Use preg_match_all()?

Imagine you want to find all occurrences of email addresses in a long text. With preg_match_all(), you can quickly get an array of all matches, making your code more efficient and readable. πŸ’‘

Basic Usage πŸ“

php
<?php $pattern = '/example/'; $subject = 'This is an example string. Another example is here.'; preg_match_all($pattern, $subject, $matches); print_r($matches); ?>

In this example, /example/ is the pattern we're searching for, and $subject is the string we're searching in. The function returns an array containing all matches.

RegEx Basics πŸ“

Regular expressions (regex) are a powerful tool for pattern matching within strings. PHP supports a wide range of regex patterns. We won't go into too much detail here, but understanding basic regex is essential for using preg_match_all().

Special Characters πŸ“

  • ^ starts the match at the beginning of the string
  • $ ends the match at the end of the string
  • \w matches any word character (alphanumeric or underscore)
  • \s matches any whitespace character
  • . matches any character except a newline

Quantifiers πŸ“

  • * matches zero or more of the preceding character
  • + matches one or more of the preceding character
  • ? matches zero or one of the preceding character
  • {n} matches exactly n of the preceding character
  • {n,} matches at least n of the preceding character
  • {n,m} matches between n and m of the preceding character

Advanced Example πŸ“

Let's find all email addresses in a string using preg_match_all().

php
<?php $pattern = '/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/'; $subject = 'Please send email to john.doe@example.com, jane_doe@example.co.uk, and info@mywebsite.com.'; preg_match_all($pattern, $subject, $matches); print_r($matches[0]); ?>

In this example, we've created a pattern for email addresses using regex. The \b anchors ensure we match whole words and not parts of other words.

Quiz πŸ“

Quick Quiz
Question 1 of 1

What does the `preg_match_all()` function do in PHP?

We hope you enjoyed this tutorial! With practice, you'll become a regex pro in no time. Happy coding! πŸ’‘πŸŽ―