0
0
PHPprogramming~15 mins

Capturing groups and backreferences in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Capturing groups and backreferences
📖 Scenario: You are working on a PHP script that processes text to find repeated words. This is useful for cleaning up typos or emphasizing repeated words in a sentence.
🎯 Goal: Build a PHP script that uses a regular expression with capturing groups and backreferences to find repeated words in a string.
📋 What You'll Learn
Create a string variable with a sentence containing repeated words.
Create a regular expression pattern using capturing groups to detect repeated words.
Use the pattern with preg_match_all to find all repeated words.
Print the repeated words found.
💡 Why This Matters
🌍 Real World
Detecting repeated words helps clean up text input, improve readability, and catch typing errors automatically.
💼 Career
Understanding capturing groups and backreferences is essential for text processing, data validation, and building search or cleanup tools in PHP.
Progress0 / 4 steps
1
Create the input string
Create a string variable called text with the value "This is is a test test sentence.".
PHP
Need a hint?

Use double quotes for the string and assign it to $text.

2
Create the regex pattern with capturing groups
Create a variable called pattern and assign it the regex string "/\b(\w+) \1\b/" which uses a capturing group and a backreference to find repeated words.
PHP
Need a hint?

The pattern uses \b for word boundaries, (\w+) to capture a word, and \1 to match the same word again.

3
Find all repeated words using preg_match_all
Use preg_match_all with $pattern and $text to find all matches. Store the matches in a variable called matches.
PHP
Need a hint?

Use preg_match_all function with the pattern and text variables, and pass $matches as the third argument to collect results.

4
Print the repeated words found
Print the repeated words found by accessing $matches[0] using print_r.
PHP
Need a hint?

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