Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to replace text in a string

Short answer

str_replace() replaces every occurrence of a substring:

<?php
 
echo str_replace('cat', 'dog', 'My cat sleeps');

Output:

My dog sleeps

Several replacements at once

Pass arrays: each element of the first is replaced by the matching element of the second.

<?php
 
echo str_replace(['red', 'green'], ['RED', 'GREEN'], 'red and green');

Output:

RED and GREEN

Ignoring case

str_ireplace() replaces ASCII letters regardless of case:

<?php
 
echo str_ireplace('HELLO', 'Hi', 'hello, world');

Output:

Hi, world

Functions used in this recipe

  • str_replace — Replaces all occurrences of a substring with another string.

Thanks for reading!

Donate to the site — we work hard for you.