The str_replace()
function is a built-in function in PHP that replaces all occurrences of a search string with a replacement string in a given string. It returns a new string with the replacements made.
Example 1: Replacing a Single Occurrence of a String
Here is an example of using str_replace()
to replace a single occurrence of a string:
$string = 'Hello, World!'; $old_string = 'Hello'; $new_string = 'Hi'; $new_string = str_replace($old_string, $new_string, $string); echo $new_string; // Output: Hi, World!
In this example, we use str_replace()
to replace the first occurrence of the string Hello
in the string Hello, World!
with the string Hi
. The resulting string is Hi, World!
.
Example 2: Replacing Multiple Occurrences of a String
Here is an example of using str_replace()
to replace multiple occurrences of a string:
$string = 'The quick brown fox jumps over the lazy dog.'; $old_string = 'o'; $new_string = '0'; $new_string = str_replace($old_string, $new_string, $string); echo $new_string; // Output: The quick br0wn f0x jumps 0ver the lazy d0g.
In this example, we use str_replace()
to replace all occurrences of the letter o
in the string The quick brown fox jumps over the lazy dog.
with the number 0
. The resulting string is The quick br0wn f0x jumps 0ver the lazy d0g.
.
Example 3: Replacing Case-Insensitive
Here is an example of using str_replace()
to replace a string case-insensitively:
$string = 'Hello, World!'; $old_string = 'hello'; $new_string = 'Hi'; $new_string = str_ireplace($old_string, $new_string, $string); echo $new_string; // Output: Hi, World!
In this example, we use str_ireplace()
instead of str_replace()
to replace the string hello
in the string Hello, World!
with the string Hi
, but in a case-insensitive way. The resulting string is Hi, World!
.
Conclusion
The str_replace()
function is a powerful tool for replacing occurrences of a search string with a replacement string in a given string in PHP. By using this function, you can easily manipulate strings to meet your needs, helping to improve the functionality and versatility of your PHP applications.