PHP String Search and Replace Practice Question with Solutions

Introduction

PHP provides useful functions to search for specific text inside a string and replace existing text with new content. These functions are commonly used to update product names, correct employee records, find keywords in messages, and clean user input. In this chapter, you will solve practical PHP String Search and replace practice question with solutions using strpos(), stripos(), strrpos(), str_replace(), and str_ireplace().

Question 1: Find the Position of a Word Using strpos()

Problem Statement

Write a PHP program to find the position of the word "PHP" inside the string "I am learning PHP".

PHP Solution

<?php
$text = "I am learning PHP";

$position = strpos($text, "PHP");

if ($position !== false) {
    echo "Word found at position: " . $position;
} else {
    echo "Word not found.";
}
?>

Sample Output

Word found at position: 13

Explanation

The strpos() function searches for the first occurrence of a string inside another string.

Its basic syntax is:

strpos(string, search)

In this example, "PHP" begins at index 13. PHP string positions start from 0, so the position is not the same as a one-based character count.

The condition $position !== false checks whether the word was found. This strict comparison is important because strpos() can return 0 when a match occurs at the beginning of a string.

Concepts Covered

  • strpos() function
  • Searching for text
  • String positions
  • Strict comparison with false

Question 2: Check Whether a Word Exists in a Message

Problem Statement

A company receives customer messages. Write a PHP program to check whether the message "Your order has been shipped" contains the word "shipped".

PHP Solution

<?php
$message = "Your order has been shipped";

if (strpos($message, "shipped") !== false) {
    echo "Shipping update found.";
} else {
    echo "Shipping update not found.";
}
?>

Sample Output

Shipping update found.

Explanation

The program uses strpos() to search for "shipped" in the customer message.

If the word exists, strpos() returns its position. Otherwise, it returns false.

The if-else statement displays the appropriate message based on the search result.

This approach is useful when checking whether a message contains a particular keyword.

Concepts Covered

  • Searching inside messages
  • strpos() function
  • if-else statements
  • Boolean conditions

Question 3: Search for Text Without Case Sensitivity Using stripos()

Problem Statement

Write a PHP program to search for the word "python" inside the sentence "I am learning PYTHON programming" without treating uppercase and lowercase letters differently.

PHP Solution

<?php
$text = "I am learning PYTHON programming";

$position = stripos($text, "python");

if ($position !== false) {
    echo "Word found at position: " . $position;
} else {
    echo "Word not found.";
}
?>

Sample Output

Word found at position: 14

Explanation

The stripos() function searches for text without case sensitivity when matching ordinary English letters.

Therefore, "python" matches "PYTHON" even though the letter cases are different.

Like strpos(), stripos() returns the position of the first match or false if no match is found.

Concepts Covered

  • stripos() function
  • Case-insensitive searching
  • String positions
  • Search conditions

Question 4: Find the Last Occurrence of a Word Using strrpos()

Problem Statement

A website stores page paths in strings. Write a PHP program to find the last occurrence of the character "/" in the path "/courses/php/practice".

PHP Solution

<?php
$path = "/courses/php/practice";

$position = strrpos($path, "/");

if ($position !== false) {
    echo "Last slash position: " . $position;
} else {
    echo "Slash not found.";
}
?>

Sample Output

Last slash position: 12

Explanation

The strrpos() function searches for the last occurrence of a character or substring.

The path contains three slash characters. Their indexes are 0, 8, and 12.

Therefore, the last slash appears at index 12.

This function can help locate the final separator in a file path or URL-like string. It does not validate the path itself.

Concepts Covered

  • strrpos() function
  • Finding the last occurrence
  • String indexing
  • Path processing

Question 5: Replace a Word Using str_replace()

Problem Statement

A training institute wants to update a course description. Write a PHP program to replace "Basic PHP" with "Advanced PHP" in the sentence "I am studying Basic PHP".

PHP Solution

<?php
$description = "I am studying Basic PHP";

$updatedDescription = str_replace(
    "Basic PHP",
    "Advanced PHP",
    $description
);

echo "Original: " . $description . "<br>";
echo "Updated: " . $updatedDescription;
?>

Sample Output

Original: I am studying Basic PHP
Updated: I am studying Advanced PHP

Explanation

The str_replace() function searches for specific text and replaces matching occurrences.

Its basic syntax is:

str_replace(search, replace, subject)

  • search: the text to find.
  • replace: the replacement text.
  • subject: the original string to process.

In this example, "Basic PHP" is replaced with "Advanced PHP".

The original variable remains unchanged because the function returns the updated string, which is stored in $updatedDescription.

Concepts Covered

  • str_replace() function
  • Replacing text
  • Function arguments
  • Storing updated strings

Question 6: Replace All Occurrences of a Word

Problem Statement

A company uses the word "Old" several times in a product description. Write a PHP program to replace every occurrence of "Old" with "New".

PHP Solution

<?php
$description = "Old model, Old design, Old packaging";

$updatedDescription = str_replace(
    "Old",
    "New",
    $description
);

echo $updatedDescription;
?>

Sample Output

New model, New design, New packaging

Explanation

By default, str_replace() replaces all matching occurrences in the subject string.

Here, "Old" appears three times, so every occurrence becomes "New".

The function performs a case-sensitive search. For example, "old" in lowercase would not match "Old" with an uppercase O.

Concepts Covered

  • Replacing multiple occurrences
  • str_replace() function
  • Case-sensitive matching
  • Updating descriptions

Question 7: Replace Text Without Case Sensitivity Using str_ireplace()

Problem Statement

A website stores course descriptions with inconsistent capitalization. Write a PHP program to replace every occurrence of "php" with "PHP" in the string "php is popular. I am learning PHP" without treating uppercase and lowercase letters differently.

PHP Solution

<?php
$text = "php is popular. I am learning PHP";

$updatedText = str_ireplace(
    "php",
    "PHP",
    $text
);

echo $updatedText;
?>

Sample Output

PHP is popular. I am learning PHP

Explanation

The str_ireplace() function replaces matching text without case sensitivity.

In this example, the lowercase "php" is replaced with uppercase "PHP". The existing uppercase "PHP" also matches, but its replacement looks identical to the original text.

This function is useful for standardizing text when the original capitalization may vary.

Concepts Covered

  • str_ireplace() function
  • Case-insensitive replacement
  • String standardization
  • Updating text

Question 8: Count How Many Replacements Were Made

Problem Statement

A product description contains the word "Laptop" several times. Write a PHP program to replace "Laptop" with "Notebook" and display the number of replacements made.

PHP Solution

<?php
$description = "Laptop bag for Laptop users. Laptop sale today.";

$updatedDescription = str_replace(
    "Laptop",
    "Notebook",
    $description,
    $count
);

echo "Updated Description: " . $updatedDescription . "<br>";
echo "Replacements Made: " . $count;
?>

Sample Output

Updated Description: Notebook bag for Notebook users. Notebook sale today.
Replacements Made: 3

Explanation

The fourth argument of str_replace() is optional. When a variable is provided, PHP stores the total number of replacements made in that variable.

In this example, "Laptop" appears three times, so $count becomes 3.

This is useful when updating product descriptions, text records, or other content where you need to know how many replacements occurred.

Concepts Covered

  • str_replace() function
  • Optional count parameter
  • Counting replacements
  • Product description updates

Question 9: Replace a Word in an Employee Record

Problem Statement

An employee record contains an outdated department name. Write a PHP program to replace "Marketing" with "Digital Marketing" in the employee information string.

PHP Solution

<?php
$employee = "Name: Rahul, Department: Marketing";

$updatedEmployee = str_replace(
    "Marketing",
    "Digital Marketing",
    $employee
);

echo "Original Record: " . $employee . "<br>";
echo "Updated Record: " . $updatedEmployee;
?>

Sample Output

Original Record: Name: Rahul, Department: Marketing
Updated Record: Name: Rahul, Department: Digital Marketing

Explanation

The program searches for "Marketing" in the employee record and replaces it with "Digital Marketing".

The rest of the string remains unchanged.

This is a simple example of updating text in a record. In a real database, structured employee fields should generally be updated directly rather than modifying a combined display string.

Concepts Covered

  • String replacement
  • Employee records
  • str_replace() function
  • Updating stored text

Question 10: Search for a Word and Replace It Only If Found

Problem Statement

A website stores the message "Welcome to our old website". Write a PHP program to search for "old" and replace it with "new" only when the word exists in the message.

PHP Solution

<?php
$message = "Welcome to our old website";
$searchWord = "old";

if (strpos($message, $searchWord) !== false) {
    $message = str_replace($searchWord, "new", $message);
    echo "Updated Message: " . $message;
} else {
    echo "Search word not found.";
}
?>

Sample Output

Updated Message: Welcome to our new website

Explanation

The program first uses strpos() to check whether "old" exists in the message.

If the word is found, str_replace() replaces it with "new". The updated string is assigned back to $message.

If the word does not exist, the program displays "Search word not found."

The strict comparison !== false ensures that a match at index 0 is also recognized.

Concepts Covered

  • strpos() function
  • str_replace() function
  • Conditional replacement
  • Strict comparison
  • Practical string processing

Key Takeaways

  • strpos() finds the first occurrence of a substring and is case-sensitive.
  • stripos() finds the first occurrence without case sensitivity.
  • strrpos() finds the last occurrence of a substring and is case-sensitive.
  • str_replace() replaces all matching occurrences by default.
  • str_ireplace() replaces matching text without case sensitivity.
  • String positions start at index 0.
  • Search functions can return false when no match is found.
  • Always use !== false when checking whether strpos() or similar search functions found a match.
  • The optional fourth argument of str_replace() can count replacements.
  • You can combine search and replacement functions to create useful text-processing programs.

Frequently Asked Questions (FAQs)

1. What is string searching in PHP?

String searching means finding whether a character or substring exists inside another string and, if found, determining its position. PHP provides functions such as strpos(), stripos(), and strrpos() for this purpose.

2. What does the strpos() function do?

The strpos() function returns the position of the first occurrence of a substring within a string. It returns false if the substring is not found.

<?php
echo strpos("Hello PHP", "PHP");
?>

Output:

6

3. What is the difference between strpos() and stripos()?

strpos() performs a case-sensitive search, while stripos() performs a case-insensitive search.

For example, searching for "php" in "Learn PHP" will not find a match using strpos(), but stripos() will find one.

4. What is the difference between strpos() and strrpos()?

strpos() returns the position of the first occurrence of a substring, while strrpos() returns the position of the last occurrence.

5. What does the str_replace() function do?

The str_replace() function replaces matching text in a string.

<?php
echo str_replace("Red", "Blue", "Red Shirt");
?>

Output:

Blue Shirt

6. Does str_replace() replace every occurrence?

Yes. By default, str_replace() replaces all matching occurrences in the subject string.

<?php
echo str_replace("cat", "dog", "cat and cat");
?>

Output:

dog and dog

7. What is the difference between str_replace() and str_ireplace()?

str_replace() matches text with case sensitivity, while str_ireplace() matches text without case sensitivity.

For example, str_ireplace("php", "PHP", "I like PHP") matches "PHP" even though the search term is lowercase.

8. How do you check whether a word exists before replacing it?

Use strpos() with a strict comparison and call str_replace() when a match is found.

<?php
$text = "Learn PHP";

if (strpos($text, "PHP") !== false) {
    echo str_replace("PHP", "Python", $text);
}
?>

Output:

Learn Python

9. Can PHP count the number of replacements made?

Yes. You can pass a variable as the fourth argument to str_replace() or str_ireplace(). PHP stores the number of replacements in that variable.

10. Are PHP string search and replace functions case-sensitive?

It depends on the function. strpos(), strrpos(), and str_replace() are case-sensitive. stripos() and str_ireplace() perform case-insensitive matching for ordinary English letters.

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

Scroll to Top