![]() |
VOOZH | about |
Given a string containing some words the task is to replace all the occurrences of a word within the given string str in PHP. To do this task, we have the following methods in PHP:
Table of Content
Thestr_replace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str.
Syntax:
str_replace( $searchVal, $replaceVal, $subjectVal, $count )Example:
GEEKS for Geeks
The str_ireplace() method is used to replace all the occurrences of the word W1 by replacing word W2 in the given string str. The difference between str_replace() and str_ireplace() is that str_ireplace() is a case-insensitive.
Syntax:
str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )Example:
GEEKS for GEEKS
Thepreg_replace() method is used to perform a regular expression for search and replace the content.
Syntax:
preg_replace( $pattern, $replacement, $subject, $limit, $count )Example:
geeks for Geeks
Using strtr() in PHP replaces specified words or characters in a string. It accepts an array where keys are search strings and values are replacements, ensuring precise substitution
Example: In this example we replaces the substring "World" with "PHP" in the string "Hello, World!" using strtr() and prints the modified string: "Hello, PHP!".
Hello, PHP!
The preg_replace_callback() function in PHP allows for replacing occurrences of a pattern in a string using a callback function. This method is particularly useful when you need to perform more complex replacements or transformations based on each match found.
Example: In this example, we will replace all occurrences of the word "apple" with "orange" in a given string using preg_replace_callback().
I have an APPLE, he has an APPLE, she likes apples.
The substr_replace() method in PHP allows you to replace a part of a string with another string. While it's typically used for more specific replacements by specifying start and length parameters, it can be adapted to replace all occurrences of a word by looping through the string.
Example
Hello PHP! PHP is beautiful.