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 sleepsSeveral 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 GREENIgnoring case
str_ireplace() replaces ASCII letters regardless of case:
<?php
echo str_ireplace('HELLO', 'Hi', 'hello, world');Output:
Hi, worldFunctions used in this recipe
- str_replace — Replaces all occurrences of a substring with another string.