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


To replace a word with a different symbol in a sentence, the PHP code is as follows −

Example

 Live Demo

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

Output

The final replaced string is : is a simple only

Here, a string is defined, and the string that needs to be replaced with a different string is placed inside an array and arranged to a variable −

$my_str = "This is a sample only";
$search_str = array("sample", "This");
$replace_str = array("simple");

The ‘str_replace’ function is used to replace the value with a different specified value. The result is printed on the screen −

$result = str_replace($search_str, $replace_str, $my_str);
print_r("The final replaced string is :");
print_r($result);

Updated on: 17-Aug-2020

128 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements