0
0
PHPprogramming~15 mins

Substring extraction in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Substring extraction
📖 Scenario: Imagine you have a list of book titles, and you want to extract a short preview from each title to show on a website.
🎯 Goal: You will create a PHP program that extracts a substring (a part of a string) from each book title to create a preview snippet.
📋 What You'll Learn
Create an array of book titles
Set a variable for the length of the preview substring
Use a loop to extract the substring from each title
Print the preview snippets
💡 Why This Matters
🌍 Real World
Extracting substrings is useful for showing previews or summaries of longer text, like book titles, article headlines, or product names on websites.
💼 Career
Many programming jobs require manipulating text data, and substring extraction is a common task in web development, data processing, and user interface design.
Progress0 / 4 steps
1
Create an array of book titles
Create an array called books with these exact titles: 'The Great Gatsby', 'To Kill a Mockingbird', '1984', 'Pride and Prejudice', 'Moby-Dick'.
PHP
Need a hint?

Use square brackets [] to create the array and separate each title with commas.

2
Set the preview length
Create a variable called previewLength and set it to 10 to define how many characters to extract from each title.
PHP
Need a hint?

Use the = sign to assign the number 10 to the variable previewLength.

3
Extract substrings from each title
Use a foreach loop with variable $title to go through $books. Inside the loop, create a variable $preview that uses substr($title, 0, $previewLength) to get the first 10 characters of each title.
PHP
Need a hint?

Use foreach ($books as $title) to loop, and substr() to get the substring.

4
Print the preview snippets
Inside the foreach loop, add a print statement to display $preview followed by a newline using "\n".
PHP
Need a hint?

Use print($preview . "\n") to show each preview on its own line.