+2 votes
in Programming Languages by (40.5k points)

In a string, I want to replace a substring with another substring. What PHP function should I use?

E.g.

From

"Hello World, how are you!!"

to

"Hello India, how are you!!"

1 Answer

+1 vote
by (355k points)
selected by
 
Best answer

You can use either str_replace() or str_ireplace() function to replace some characters with some other characters in a string. str_replace() performs a case-sensitive search whereas str_ireplace() does case-insensitive search.

The syntax of the function is:

str_replace(old_substring, new_substring, original_string)

Here is an example:

<?php
$str = "Hello World, how are you!!";
echo $str;
echo "\n";
//case sensitive
echo str_replace("World", "India", $str);
echo "\n";
// case-insensitive
echo str_ireplace("world", "India", $str);
echo "\n";
?>

The above code will return the following output:

Hello World, how are you!!
Hello India, how are you!!
Hello India, how are you!!


...