PHP program to replace a word with a different symbol in a sentence

To replace a word with a different symbol in a sentence, PHP provides the str_replace() function. This function searches for specified words and replaces them with new values.

Syntax

str_replace(search, replace, subject, count)

Parameters

The str_replace() function accepts the following parameters ?

  • search − The value to search for (can be string or array)
  • replace − The replacement value (can be string or array)
  • subject − The string or array to search in
  • count − Optional variable to store the number of replacements

Example

<?php
    $my_str = "This is a sample only";
    $search_str = array("sample", "This");
    $replace_str = array("simple", "That");
    $result = str_replace($search_str, $replace_str, $my_str);
    print_r("The final replaced string is: ");
    print_r($result);
?>
The final replaced string is: That is a simple only

How It Works

In the example above ?

  1. The original string is defined: "This is a sample only"
  2. Search array contains words to find: ["sample", "This"]
  3. Replace array contains replacement words: ["simple", "That"]
  4. The function replaces "sample" with "simple" and "This" with "That"

Single Word Replacement

For replacing a single word, you can use strings instead of arrays ?

<?php
    $sentence = "PHP is difficult to learn";
    $new_sentence = str_replace("difficult", "easy", $sentence);
    echo $new_sentence;
?>
PHP is easy to learn

Conclusion

The str_replace() function is an efficient way to replace words or symbols in PHP strings. It supports both single replacements and multiple replacements using arrays.

Updated on: 2026-03-15T09:08:21+05:30

258 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements