How to replace one substring within another?

1

I found in the PHP documentation the substr_replace function but it does not do exactly what I want, it simply replaces a string that I pass as a parameter by another substring. What I want is to pass a string and within that string replace all occurrences of a given substring with another.

    
asked by anonymous 28.08.2017 / 17:29

2 answers

3

In this case, the function you need is str_replace , which replaces all occurrences of one string with another in a string.

Example:

<?php
echo str_replace("mundo", "Júlio", "Olá mundo!");
?>

This code will change the word "mundo" to "Júlio" into the string "Ola mundo!" and will print: Olá Júlio .

Official reference: link

    
28.08.2017 / 17:35
1

You can also use the strtr ("hello my name is santa", array ('hello' => 'ola'));

In this case every instance 'hello' will be changed to 'olá' .

If you want to change more than one value, you can include more items in the parameter array:

strtr ("hello my name is santa", array ('hello' => 'ola', 'is' => 'é'));

Reference: link

    
28.08.2017 / 17:40