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

PHPServer Side ProgrammingProgramming

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);
raja
Published on 17-Aug-2020 11:25:08
Advertisements