0
0
PHPprogramming~30 mins

Lookahead and lookbehind in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Lookahead and Lookbehind
📖 Scenario: You are working with text data and want to find specific patterns using PHP regular expressions. Lookahead and lookbehind help you find matches based on what comes before or after a pattern without including those parts in the match.
🎯 Goal: Build a PHP script that uses lookahead and lookbehind in regular expressions to find words that meet certain conditions in a sentence.
📋 What You'll Learn
Create a string variable with a sentence containing multiple words.
Create a pattern using positive lookahead to find words followed by a specific character.
Create a pattern using positive lookbehind to find words preceded by a specific character.
Print the matched words for both patterns.
💡 Why This Matters
🌍 Real World
Lookahead and lookbehind are useful in text processing, such as searching for words that appear before or after certain characters without including those characters in the result.
💼 Career
Understanding these regex features helps in jobs involving data cleaning, validation, and complex text searches, common in web development and data analysis.
Progress0 / 4 steps
1
Create the sentence string
Create a string variable called sentence with the exact value: "apple banana cherry date".
PHP
Need a hint?

Use $sentence = "apple banana cherry date"; to create the string.

2
Create a lookahead pattern
Create a variable called pattern_lookahead with the regex pattern that matches words followed by a space and the letter c using positive lookahead: /\b\w+(?= c)/.
PHP
Need a hint?

Use $pattern_lookahead = '/\b\w+(?= c)/'; to create the lookahead pattern.

3
Create a lookbehind pattern
Create a variable called pattern_lookbehind with the regex pattern that matches words preceded by the letter a and a space using positive lookbehind: /\b(?<=a )\w+/.
PHP
Need a hint?

Use $pattern_lookbehind = '/\b(?<=a )\w+/'; to create the lookbehind pattern.

4
Find and print matches
Use preg_match_all with $pattern_lookahead and $pattern_lookbehind on $sentence to find matches. Store matches in $matches_lookahead and $matches_lookbehind. Then print the matches using print_r for both variables.
PHP
Need a hint?

Use preg_match_all($pattern_lookahead, $sentence, $matches_lookahead); and preg_match_all($pattern_lookbehind, $sentence, $matches_lookbehind); then print with print_r($matches_lookahead[0]); and print_r($matches_lookbehind[0]);.