Replace A Word In A String In PHP
Code snippet for how to Replace A Word In A String In PHP with sample and detail explanation
Working with strings is a common task in any programming language and PHP is no different. In this article, we will explore how to replace a word in a string using PHP, a very handy function that can be used in numerous scenarios.
Code Snippet
In PHP, there is a built-in function called str_replace()
that can be used to replace all occurrences of the search string with the replacement string. Here is the code snippet:
<?php
$str = "Hello world!";
$new_str = str_replace("world", "readers", $str);
echo $new_str;
?>
Running this code will display “Hello readers!“.
Code Explanation
Let’s look at how this code works step by step.
-
First, we define a string,
$str = "Hello world!";
. -
Following that, we use the
str_replace()
function to replace ‘world’ with ‘readers’. Instr_replace()
, the first argument is the word you want to replace, the second argument is the new word, and the third argument is the variable containing the string.
$new_str = str_replace("world", "readers", $str);
- Finally, we use the
echo
statement to print the new string,$new_str
.
Here, our original string was Hello world!
. After applying the str_replace()
function, ‘world’ is replaced with ‘readers’, so the output is Hello readers!
.
That’s all there is to it. Replacing a word in a string is quite simple in PHP. With str_replace()
, you can easily modify strings to fit different needs in your PHP applications. It is a powerful function that will be invaluable for any coder working with PHP.