0
0
PHPprogramming~15 mins

Preg_match for pattern matching in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Preg_match for pattern matching
📖 Scenario: You are building a simple PHP script to check if a user's input contains a specific word. This is useful for filtering or validating text inputs in web forms.
🎯 Goal: Build a PHP script that uses preg_match to find if the word "hello" appears in a given string.
📋 What You'll Learn
Create a variable called text with the exact string "Say hello to the world".
Create a variable called pattern with the exact regex pattern "/hello/".
Use preg_match with $pattern and $text to check for a match and store the result in $matchFound.
Print "Match found!" if $matchFound is true, otherwise print "No match found.".
💡 Why This Matters
🌍 Real World
Pattern matching is used in web forms to validate user input, like checking if an email or phone number is correct.
💼 Career
Knowing how to use <code>preg_match</code> helps in backend web development and data validation tasks.
Progress0 / 4 steps
1
Create the text variable
Create a variable called $text and set it to the string "Say hello to the world".
PHP
Need a hint?

Use $text = "Say hello to the world"; to create the variable.

2
Create the regex pattern variable
Create a variable called $pattern and set it to the regex pattern "/hello/".
PHP
Need a hint?

Use $pattern = "/hello/"; to create the regex pattern variable.

3
Use preg_match to check for the pattern
Use preg_match with $pattern and $text to check for a match and store the result in a variable called $matchFound.
PHP
Need a hint?

Use $matchFound = preg_match($pattern, $text); to check for the pattern.

4
Print the result
Write an if statement that prints "Match found!" if $matchFound is true, otherwise print "No match found.".
PHP
Need a hint?

Use if ($matchFound) { print("Match found!"); } else { print("No match found."); } to print the result.