PHP Regex Quantifiers 🎯

beginner
9 min

PHP Regex Quantifiers 🎯

Welcome back to CodeYourCraft! Today, we're diving into the fascinating world of PHP Regular Expressions (Regex) and focusing on Quantifiers. These little helpers will enable you to repeat patterns in your Regex, making your code more efficient and powerful. Let's get started!

What are Quantifiers in PHP Regex? πŸ“

In simple terms, Quantifiers control how many times a specific character, group, or pattern should be matched. They help us to find exact matches according to the defined criteria.

Basic Quantifiers πŸ’‘

There are four basic quantifiers in PHP Regex: ?, *, +, and {n}. Let's understand them one by one.

1. ? - Zero or One Occurrence

The ? quantifier matches the preceding character zero or one time.

πŸ“ Example: To find the word 'dog' or 'do' in a string, we can use the following Regex: /dog?/.

php
$text = "I have a dog and two cats."; // Search for 'dog' or 'do' in the text $pattern = '/dog?/'; preg_match_all($pattern, $text, $matches); print_r($matches);

Output:

Array ( [0] => Array ( [0] => dog ) )

2. * - Zero or More Occurrences

The * quantifier matches the preceding character zero or more times.

πŸ“ Example: To find all occurrences of the word 'car' in a sentence, even if it's repeated multiple times, we can use the following Regex: /car*/.

php
$text = "I have a car, I love cars, and I need another car."; // Search for 'car' in the text $pattern = '/car*/'; preg_match_all($pattern, $text, $matches); print_r($matches);

Output:

Array ( [0] => Array ( [0] => car [1] => car [2] => car ) )

3. + - One or More Occurrences

The + quantifier matches the preceding character one or more times.

πŸ“ Example: To find all words starting with 'a' and having one or more letters following it in a sentence, we can use the following Regex: /a+/.

php
$text = "Apple, apricot, avocado, and many more fruits."; // Search for words starting with 'a' and having one or more letters following it $pattern = '/a+/'; preg_match_all($pattern, $text, $matches); print_r($matches);

Output:

Array ( [0] => Array ( [0] => Apple [1] => apricot [2] => avocado ) )

4. {n} - Exact Number of Occurrences

The {n} quantifier matches the preceding character exactly n times.

πŸ“ Example: To find exactly three occurrences of the letter 'o' in a string, we can use the following Regex: /ooo/.

php
$text = "This is a three-letter word with three 'o's."; // Search for exactly three occurrences of 'o' in the text $pattern = '/ooo/'; preg_match($pattern, $text, $matches); print_r($matches);

Output:

Array ( [0] => three-letter word with three 'o's. )
Quick Quiz
Question 1 of 1

Which quantifier matches the preceding character zero or more times in PHP Regex?

Greedy and Lazy Quantifiers πŸ’‘

By default, quantifiers in PHP Regex are greedy, meaning they match as much as possible. However, sometimes we may want to match the minimum occurrence instead. For this, we can use lazy quantifiers by adding a question mark (?) after the quantifier.

πŸ“ Example: Let's find all the email addresses in a text. A typical email address contains an @ symbol, followed by one or more characters, followed by a dot, and then one or more characters.

With a greedy .* quantifier, the regex might match too much and capture unwanted characters. To fix this, we can make the dot lazy by adding a question mark (.?).

php
$text = "My email addresses are example@example.com, info@example.co.uk, and support@example.net."; // Search for email addresses $pattern = '/b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}/'; preg_match_all($pattern, $text, $matches); print_r($matches);

Output:

Array ( [0] => Array ( [0] => example@example.com [1] => info@example.co.uk [2] => support@example.net ) )
Quick Quiz
Question 1 of 1

Which quantifier matches the preceding character one or more times, but as little as possible in PHP Regex?

Practice Time 🎯

Now that you've learned about PHP Regex Quantifiers, try to solve the following problems. Answers can be found in the comments below.

  1. Find all the phone numbers in the following text. A typical phone number contains numbers, spaces, hyphens, or parentheses.
php
$text = "My phone numbers are (123) 456-7890, +44 20 7890 1234, and 0987654321."; // Find phone numbers // Hint: Use a combination of character classes ([]), quantifiers, and grouping (())
  1. Find all the hashtags (#) in the following text. Hashtags can contain letters, digits, and underscores.
php
$text = "#CodeYourCraft #LearnPHP #BeginnerFriendly #Tutorial"; // Find hashtags // Hint: Use character classes ([]) and quantifiers

That's it for today! Keep practicing and don't forget to check back for more PHP tutorials on CodeYourCraft. Happy coding! πŸ’»πŸŽ‰