PHP String, Extraction and Substrings Practice Questions with Solutions

Introduction

PHP allows you to extract a specific portion of a string without displaying the entire text. This technique is useful when working with employee IDs, product codes, phone numbers, customer names, and website content. In this chapter, you will understand the concepts of PHP String Extraction and Substrings Practice Questions with Solutions using substr(), substr_replace(), and string indexing to extract or update specific parts of a string through practical PHP questions.

Question 1: Extract the First Five Characters Using substr()

Problem Statement

Write a PHP program to extract the first five characters from the string "PROGRAMMING" using the substr() function.

PHP Solution

<?php
$text = "PROGRAMMING";

$result = substr($text, 0, 5);

echo "Original String: " . $text . "<br>";
echo "Extracted Text: " . $result;
?>

Sample Output

Original String: PROGRAMMING
Extracted Text: PROGR

Explanation

The substr() function extracts a portion of a string.

Syntax:

substr(string, offset, length)
  • string: The original string.
  • offset: The position where extraction starts.
  • length: The number of characters to extract.

In this example, the offset is 0, so extraction starts at the first character. The length is 5, so PHP returns the first five characters: "PROGR".

Concepts Covered

  • substr() function
  • String extraction
  • String offsets
  • Specifying extraction length

Question 2: Extract the Last Four Characters of a String

Problem Statement

A company stores product codes in a string. Write a PHP program to extract the last four characters from the product code "PRODUCT2026".

PHP Solution

<?php
$productCode = "PRODUCT2026";

$result = substr($productCode, -4);

echo "Product Code: " . $productCode . "<br>";
echo "Last Four Characters: " . $result;
?>

Sample Output

Product Code: PRODUCT2026
Last Four Characters: 2026

Explanation

The substr() function supports negative offsets.

A negative offset counts backward from the end of the string. In this example, -4 means extraction begins four characters from the end.

Because no length is specified, PHP extracts everything from that position to the end of the string.

The result is "2026".

Concepts Covered

  • Negative offsets
  • Extracting characters from the end
  • substr() function
  • Product code processing

Question 3: Extract a Word from a Sentence

Problem Statement

Write a PHP program to extract the word "Python" from the sentence "I am learning Python programming".

PHP Solution

<?php
$sentence = "I am learning Python programming";

$result = substr($sentence, 14, 6);

echo "Original Sentence: " . $sentence . "<br>";
echo "Extracted Word: " . $result;
?>

Sample Output

Original Sentence: I am learning Python programming
Extracted Word: Python

Explanation

The word "Python" begins at index 14 in the sentence.

The program uses:

substr($sentence, 14, 6)

Here:

  • 14 is the starting index.
  • 6 is the number of characters to extract.

PHP returns six characters beginning at index 14, producing "Python".

This method is useful when the text structure and the word’s position are already known.

Concepts Covered

  • Extracting words
  • String indexing
  • substr() function
  • Starting positions and lengths

Question 4: Extract the First Name from a Full Name

Problem Statement

An employee database stores the full name "Rahul Sharma". Write a PHP program to extract the first name using substr() and strpos().

PHP Solution

<?php
$fullName = "Rahul Sharma";

$spacePosition = strpos($fullName, " ");

if ($spacePosition !== false) {
    $firstName = substr($fullName, 0, $spacePosition);
    echo "First Name: " . $firstName;
} else {
    echo "No space found in the name.";
}
?>

Sample Output

First Name: Rahul

Explanation

The strpos() function finds the position of the first space in the full name.

The substr() function then extracts the characters from the beginning of the string up to, but not including, that space.

Since "Rahul" appears before the first space, the extracted first name is "Rahul".

The condition checks whether a space exists before attempting the extraction.

Note: This is a basic example. Names can contain multiple words, so real applications may need more flexible name-handling logic.

Concepts Covered

  • substr() function
  • strpos() function
  • Combining string functions
  • Extracting names
  • Conditional statements

Question 5: Extract the Domain Name from an Email Address

Problem Statement

A company stores employee email addresses. Write a PHP program to extract the domain from the email address "rahul@gmail.com".

PHP Solution

<?php
$email = "rahul@gmail.com";

$atPosition = strpos($email, "@");

if ($atPosition !== false) {
    $domain = substr($email, $atPosition + 1);
    echo "Email: " . $email . "<br>";
    echo "Domain: " . $domain;
} else {
    echo "Invalid email format.";
}
?>

Sample Output

Email: rahul@gmail.com
Domain: gmail.com

Explanation

The strpos() function finds the position of the @ symbol.

The expression $atPosition + 1 moves the starting position to the character immediately after @.

The substr() function then extracts the remaining text, resulting in "gmail.com".

This is a basic extraction example, not complete email validation.

Concepts Covered

  • Email string processing
  • strpos() function
  • substr() function
  • Extracting text after a separator

Question 6: Extract a Year from a Product Code

Problem Statement

A company uses the product code "PRD-2026-125". Write a PHP program to extract the year "2026" from the code.

PHP Solution

<?php
$productCode = "PRD-2026-125";

$year = substr($productCode, 4, 4);

echo "Product Code: " . $productCode . "<br>";
echo "Year: " . $year;
?>

Sample Output

Product Code: PRD-2026-125
Year: 2026

Explanation

The product code follows this structure:

  • PRD-: Product prefix
  • 2026: Year
  • -125: Product number

The year starts at index 4. The program extracts four characters from that position using substr($productCode, 4, 4).

The result is "2026".

This approach works when the product code follows a consistent format.

Concepts Covered

  • Extracting data from product codes
  • Fixed-position extraction
  • substr() function
  • String formats

Question 7: Extract Text Before a Specific Character

Problem Statement

A company stores product details in the format "Laptop-45000". Write a PHP program to extract the product name before the hyphen (-).

PHP Solution

<?php
$product = "Laptop-45000";

$hyphenPosition = strpos($product, "-");

if ($hyphenPosition !== false) {
    $productName = substr($product, 0, $hyphenPosition);
    echo "Product Name: " . $productName;
} else {
    echo "Separator not found.";
}
?>

Sample Output

Product Name: Laptop

Explanation

The strpos() function finds the position of the hyphen.

The program then extracts the text from index 0 up to the hyphen’s position. Because the extraction length does not include the hyphen, the result is "Laptop".

This technique is useful when a string contains multiple pieces of information separated by a known character.

Concepts Covered

  • Extracting text before a separator
  • strpos() function
  • substr() function
  • Product data processing

Question 8: Extract Text Between Two Positions

Problem Statement

Write a PHP program to extract the characters "ABCDE" from the string "XYZABCDE123".

PHP Solution

<?php
$text = "XYZABCDE123";

$result = substr($text, 3, 5);

echo "Original String: " . $text . "<br>";
echo "Extracted Text: " . $result;
?>

Sample Output

Original String: XYZABCDE123
Extracted Text: ABCDE

Explanation

The string begins with "XYZ", which occupies indexes 0, 1, and 2.

The required text begins at index 3.

The program extracts five characters starting from index 3, giving "ABCDE".

This approach is helpful when processing strings with known positions, such as reference numbers or fixed-format codes.

Concepts Covered

  • Extracting a middle substring
  • String offsets
  • Extraction length
  • substr() function

Question 9: Replace Part of a String Using substr_replace()

Problem Statement

A company stores a product code as "PRD-12345". Write a PHP program to replace the numeric portion "12345" with "67890" using substr_replace().

PHP Solution

<?php
$productCode = "PRD-12345";

$updatedCode = substr_replace($productCode, "67890", 4, 5);

echo "Original Code: " . $productCode . "<br>";
echo "Updated Code: " . $updatedCode;
?>

Sample Output

Original Code: PRD-12345
Updated Code: PRD-67890

Explanation

The substr_replace() function replaces a portion of a string at a specified position.

Syntax:

substr_replace(string, replacement, offset, length)

In this example:

  • The original string is "PRD-12345".
  • The replacement text is "67890".
  • The starting offset is 4.
  • The length to replace is 5.

PHP replaces the five characters beginning at index 4 with "67890".

Unlike substr(), which extracts a portion of a string, substr_replace() returns a string with the selected portion replaced.

Concepts Covered

  • substr_replace() function
  • Replacing a substring
  • String offsets and lengths
  • Updating product codes

Question 10: Mask Part of a Phone Number

Problem Statement

A company wants to display a partially masked phone number for privacy. Write a PHP program to replace the first six digits of "9876543210" with asterisks (*), leaving the last four digits visible.

PHP Solution

<?php
$phone = "9876543210";

$maskedPhone = substr_replace($phone, "******", 0, 6);

echo "Original Phone: " . $phone . "<br>";
echo "Masked Phone: " . $maskedPhone;
?>

Sample Output

Original Phone: 9876543210
Masked Phone: ******3210

Explanation

The substr_replace() function replaces a selected portion of the phone number.

Here:

  • The replacement string is "******".
  • The starting offset is 0.
  • The number of characters to replace is 6.

The first six digits are replaced with asterisks, while the final four digits remain visible.

This technique can be used to display partially masked identifiers. However, masking text in the output is not a substitute for protecting the original data or controlling access to it.

Concepts Covered

  • substr_replace() function
  • Partial string replacement
  • Phone number masking
  • String positions
  • Basic privacy-aware display

Key Takeaways

  • The substr() function extracts a portion of a string.
  • The starting offset determines where extraction begins.
  • The optional length determines how many characters are extracted.
  • A negative offset counts backward from the end of the string.
  • The strpos() function can help locate a separator before extracting text.
  • Combining strpos() and substr() allows you to extract information from structured strings.
  • The substr_replace() function replaces a portion of a string.
  • String extraction is useful for processing names, email addresses, product codes, and phone numbers.
  • Always check whether a separator exists before relying on its position.
  • Ordinary PHP string offsets operate on bytes, so multibyte UTF-8 text may require additional care.

Frequently Asked Questions (FAQs)

1. What is the substr() function in PHP?

The substr() function returns a portion of a string based on a starting offset and an optional length.

<?php
echo substr("Programming", 0, 4);
?>

Output:

Prog

2. What is the syntax of substr()?

The syntax is:

substr(string, offset, length)

The string is the original text, offset identifies where extraction begins, and length specifies how many bytes to extract. The length is optional.

3. How do you extract the last three characters of a string?

Use a negative offset of -3.

<?php
echo substr("Computer", -3);
?>

Output:

ter

4. Can substr() use a negative starting position?

Yes. A negative offset counts backward from the end of the string.

For example, substr("Programming", -4) returns "ming".

5. What happens if the length parameter is omitted?

If the length is omitted, PHP returns the substring from the specified starting offset to the end of the string.

<?php
echo substr("Hello World", 6);
?>

Output:

World

6. What is the difference between substr() and substr_replace()?

substr() extracts and returns a portion of a string. substr_replace() replaces a specified portion and returns the updated string.

7. How do you extract the first name from a full name?

You can find the first space using strpos() and then extract the text before it using substr().

<?php
$name = "Amit Sharma";
$position = strpos($name, " ");

if ($position !== false) {
    echo substr($name, 0, $position);
}
?>

Output:

Amit

This simple example assumes the first name appears before the first space.

8. How can you extract the domain from an email address?

Find the position of @ using strpos() and extract the remaining text using substr().

For "student@example.com", the extracted domain is "example.com".

9. What happens if the starting offset is outside the string?

If the starting offset is beyond the string’s length, substr() generally returns an empty string. Negative offsets are calculated relative to the end of the string.

10. Can substr() work correctly with Hindi text and emojis?

Not necessarily. PHP’s standard substr() function works with byte offsets, which may split a multibyte UTF-8 character.

For Unicode-aware extraction, consider mb_substr() when the PHP mbstring extension is available.

<?php
$text = "Hello";
echo mb_substr($text, 0, 3, "UTF-8");
?>

Output:

Hel

This example uses English text. The same function can also handle multibyte text more appropriately than substr().

Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.

Scroll to Top