PHP's str_replace() made simple
Table of contents:
The basics of the str_replace() function in PHP
- Practical use cases of str_replace() in PHP
The limitations of the str_replace() function in PHP
PHP provides a plethora of built-in functions, with
str_replace() being one of the my favorite.
This function is fundamental to handling and manipulating strings, playing an essential role in many PHP applications.
str_replace() function in PHP replaces strings with other strings. It’s that simple, yet powerful.
Its signature looks like this:
str_replace(string|array $search,string|array $replace,string|array $subject,int &$count = null) : string|array
search: It specifies the value to find. It can either be a
replace: It defines the value to replace the found value with. It can either be a
subject: It’s the string or array to be searched and replaced on. It can either be a
count: It’s an optional
integerand determines the number of replacements performed.
To me, examples speak more than theory. Let’s explore how to use
Let’s say we have a greeting “Hello, unknown person!” and we want to change “unknown person” to “Benjamin”.
str_replace(), we can achieve this like so:
$sentence = 'Hello, unknown person!';echo str_replace('unknown person', 'Benjamin', $sentence);// Outputs: Hello, Benjamin!
str_replace() can also be used with arrays, sequencially searching and replacing the values.
This can avoid you to call
str_replace() multiple times.
$sentence = '1st, 2nd, and 3rd.';echo str_replace(['1st', '2nd', '3rd'],['first', 'second', 'third'],$sentence);// Outputs: first, second, and third.
str_replace() accepts a value of type
array as the subject.
Which means you can still avoid calling
str_replace multiple times if you are able to build an array of subjects. I didn’t know that before writing this article!
Let me show you:
$sentences = ['You cannot mention Mastodon on Twitter!',"Let's build a new society on Mastodon!",'Is Mastodon a Twitter-killer?',];var_dump(str_replace('Mastodon','@&$!?%',$sentences));// Outputs: [// 'You cannot mention @&$!?% on Twitter!',// "Let's build a new society on @&$!?%!",// 'Is @&$!?% a Twitter-killer?',// ]
The str_replace() function is case-sensitive.
If you need case-insensitive replacement, PHP offers the
echo str_ireplace('foo', 'bar', 'FOo foo fOO');// Outputs: bar bar baz
str_replace() has its limitations:
No direct support for regular expressions: As mentioned,
str_replace()does not support regex. For this, you’ll need to use
It’s unable to replace multi-byte unicode characters: The
str_replace()function is not safe for multi-byte characters like those found in UTF-8 strings.
There are problems with case sensitivity: As noted before,
str_replace()is case-sensitive. If you need to ignore case, use