Replace Multiple Words In A String In PHP
Code snippet for how to Replace Multiple Words In A String In PHP with sample and detail explanation
In this article, we will demonstrate how to replace multiple words in a string using PHP. This is a vital operation when manipulating text in PHP, where a word needs to get replaced with another for various reasons such as data cleaning or standardization.
Code snippet for String Replacement in PHP
Below is a simple piece of code that allows you to replace multiple words in a string.
<?php
function replace_multiple_words($find, $replace, $string){
return str_replace($find, $replace, $string);
}
$find=array('apple','orange','banana');
$replace=array('fruit1','fruit2','fruit3');
$string="apple is my first favorite fruit, orange is my second and banana is my third.";
echo replace_multiple_words($find, $replace, $string);
?>
Code Explanation for String Replacement in PHP
Let’s break the code down step by step.
In the PHP code snippet above, we first define a function called replace_multiple_words
taking three parameters: $find
, $replace
, and $string
.
This function uses the PHP function str_replace
that takes the same three parameters: $find
, $replace
, and $string
.
The str_replace
function in PHP replaces some characters with some other characters in a string.
We then define three arrays:
$find
: contains the word(s) we want to replace in a string. For this example, it’s ‘apple’, ‘orange’, and ‘banana’.$replace
: contains the word(s) we want to replace the word(s) in the find array with. It’s ‘fruit1’, ‘fruit2’, and ‘fruit3’ in this example.$string
: is the text we want to execute the replace operation on.
Finally, the echo
statement calls our function replace_multiple_words()
.
When this script is executed, each word from the $find
array found in the $string
will be replaced by the corresponding word in the $replace
array. The output will be:
‘fruit1 is my first favorite fruit, fruit2 is my second and fruit3 is my third.’
This way we can replace multiple words from a string in PHP. The simplicity and flexibility of replace operations in PHP make it a useful tool in any developer’s toolkit.