0
0
PHPprogramming~15 mins

Preg_match_all for global matching in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using preg_match_all for Global Matching in PHP
📖 Scenario: You have a paragraph of text and want to find all the words that start with the letter 'a'.
🎯 Goal: Build a PHP script that uses preg_match_all to find all words starting with 'a' in a given text.
📋 What You'll Learn
Create a string variable called text with the exact sentence: "An apple a day keeps the doctor away."
Create a variable called pattern that holds the regex pattern to find words starting with 'a' (case-insensitive).
Use preg_match_all with pattern and text to find all matches and store them in matches.
Print the array matches[0] which contains all matched words.
💡 Why This Matters
🌍 Real World
Finding all occurrences of a pattern in text is useful in text analysis, search engines, and data extraction.
💼 Career
Many programming jobs require working with text data and using regular expressions to extract information efficiently.
Progress0 / 4 steps
1
DATA SETUP: Create the text string
Create a string variable called text and set it to the exact sentence: "An apple a day keeps the doctor away."
PHP
Need a hint?

Use double quotes to create the string exactly as shown.

2
CONFIGURATION: Create the regex pattern
Create a variable called pattern and set it to the regex pattern "/\ba\w*/i" to find words starting with 'a' (case-insensitive).
PHP
Need a hint?

The pattern /\ba\w*/i means words starting with 'a' ignoring case.

3
CORE LOGIC: Use preg_match_all to find matches
Use preg_match_all with pattern and text to find all matches and store them in a variable called matches.
PHP
Need a hint?

Use preg_match_all with the pattern, text, and matches variables.

4
OUTPUT: Print the matched words
Print the array matches[0] which contains all matched words using print_r.
PHP
Need a hint?

Use print_r($matches[0]) to display the matched words array.