How to replace one substring within a string with another?

Asked

Viewed 654 times

1

I found in the documentation of PHP the function substr_replace but it doesn’t 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.

2 answers

3

In this case, the function you need is the 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" for "Júlio" in string "Ola mundo!" and will print: Olá Júlio.

Official reference: http://php.net/manual/en/function.str-replace.php

  • 1

    True, and that one, it was hard to find that manual and a mess, thank you.

1

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

In this case all occurrence 'hello' will be exchanged for '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: http://php.net/manual/en/function.strtr.php

  • With this function I can search for more than one substring? If yes it will be very useful.

  • @Júliosouzapereira yes, you can put as many arguments as you want inside the array. I will improve the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.