0
0
PHPprogramming~15 mins

Character classes and quantifiers in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Character classes and quantifiers
📖 Scenario: You are working on a simple PHP script to check if certain words match a pattern. This is useful when you want to find words that follow specific rules, like starting with a vowel or having a certain number of letters.
🎯 Goal: Build a PHP script that uses regular expressions with character classes and quantifiers to find words that start with a vowel and have exactly 5 letters.
📋 What You'll Learn
Create a list of words in a PHP array called $words with the exact values: 'apple', 'banana', 'grape', 'orange', 'pear', 'peach'
Create a variable called $pattern that holds a regular expression to match words starting with a vowel (a, e, i, o, u) and having exactly 5 letters
Use a foreach loop with the variable $word to go through each word in $words
Inside the loop, use preg_match with $pattern and $word to check if the word matches the pattern
Print each matching word on its own line using echo
💡 Why This Matters
🌍 Real World
Regular expressions help filter and find text patterns in data, like validating user input or searching documents.
💼 Career
Knowing how to use character classes and quantifiers in regex is useful for web developers, data analysts, and anyone working with text processing.
Progress0 / 4 steps
1
Create the list of words
Create a PHP array called $words with these exact words: 'apple', 'banana', 'grape', 'orange', 'pear', 'peach'
PHP
Need a hint?

Use square brackets [] to create an array and separate words with commas.

2
Create the regular expression pattern
Create a variable called $pattern that holds the regular expression '/^[aeiou]\w{4}$/' to match words starting with a vowel and having exactly 5 letters
PHP
Need a hint?

The pattern starts with ^ for start of word, then a character class [aeiou] for vowels, then \w{4} for exactly 4 word characters, and $ for end of word. Use the i modifier for case-insensitive matching.

3
Check each word with the pattern
Use a foreach loop with variable $word to go through $words. Inside the loop, use preg_match($pattern, $word) to check if the word matches the pattern.
PHP
Need a hint?

Use foreach ($words as $word) to loop and preg_match($pattern, $word) to test each word.

4
Print the matching words
Inside the if block, use echo $word . "\n"; to print each matching word on its own line.
PHP
Need a hint?

Use echo $word . "\n"; to print each word on a new line.