0
0
PHPprogramming~15 mins

Preg_replace for substitution in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Preg_replace for substitution
📖 Scenario: You are working on a simple text editor tool that needs to replace certain words in a sentence with new words. This is a common task when cleaning or updating text data.
🎯 Goal: Build a PHP script that uses preg_replace to substitute specific words in a given sentence with new words.
📋 What You'll Learn
Create a variable $sentence with the exact text: "The cat sat on the mat."
Create a variable $pattern that matches the word "cat"
Create a variable $replacement with the text "dog"
Use preg_replace with $pattern, $replacement, and $sentence to create a new variable $new_sentence
Print the value of $new_sentence
💡 Why This Matters
🌍 Real World
Text substitution is useful in editing documents, cleaning data, or customizing messages automatically.
💼 Career
Many programming jobs require manipulating text data, and knowing how to use regular expressions with functions like <code>preg_replace</code> is a valuable skill.
Progress0 / 4 steps
1
DATA SETUP: Create the initial sentence
Create a variable called $sentence and set it to the string "The cat sat on the mat." exactly.
PHP
Need a hint?

Use double quotes to create the string exactly as shown.

2
CONFIGURATION: Define the pattern and replacement
Create a variable called $pattern and set it to the regex pattern that matches the word "cat" exactly. Then create a variable called $replacement and set it to the string "dog".
PHP
Need a hint?

Remember to put the pattern between slashes / for regex in PHP.

3
CORE LOGIC: Use preg_replace to substitute the word
Use preg_replace with $pattern, $replacement, and $sentence to create a new variable called $new_sentence.
PHP
Need a hint?

Use the syntax: preg_replace(pattern, replacement, subject).

4
OUTPUT: Print the new sentence
Write a print statement to display the value of $new_sentence.
PHP
Need a hint?

Use print($new_sentence); to show the result.