replace.php
Table of Contents
Functions
- replace() : string
- Replaces all occurrences of a substring within a string, with optional Unicode (grapheme-safe) and normalization support.
Functions
replace()
Replaces all occurrences of a substring within a string, with optional Unicode (grapheme-safe) and normalization support.
replace(string|null $source, string $from, string $to[, bool $ignoreCase = false ][, bool $utf8 = false ]) : string
This function handles both simple ASCII strings and full Unicode strings.
When $utf8 is enabled, the function:
- Normalizes the source string and the search string using Unicode Normalization Form C (NFC),
- Uses grapheme-aware functions (
grapheme_strpos/grapheme_stripos,grapheme_substr) to correctly handle composed characters and surrogate pairs.
When $utf8 is disabled, a faster str_replace or str_ireplace is used.
If $ignoreCase is true, the search is performed in a
case-insensitive, Unicode-aware manner (when $utf8 is true) or ASCII case-insensitive otherwise.
Examples
Simple replacement:
replace('Hello World', 'World', 'Marc');
// "Hello Marc"
Unicode-safe replacement:
replace('école', 'é', 'E' , utf8:true );
// "Ecole"
Emoji replacement (surrogate pairs):
replace('I ❤️ PHP', '❤️', '💛', false, true);
// Returns "I 💛 PHP"
Case-insensitive replacement:
replace('Straße', 'STRASSE', 'Street', ignoreCase: true , utf8: true );
Null source:
replace(null, 'foo', 'bar');
// Returns ""
Parameters
- $source : string|null
-
The source string to process. If
null, an empty string is assumed. - $from : string
-
The substring to search for. Must be a valid UTF-8 string.
- $to : string
-
The replacement string.
- $ignoreCase : bool = false
-
Whether the search should be performed in a case-insensitive way.
- $utf8 : bool = false
-
Whether to enable Unicode-aware, normalization-safe replacement.
Tags
Return values
string —The resulting string after replacement.