VOOZH about

URL: https://www.geeksforgeeks.org/php/how-to-replace-a-word-inside-a-string-in-php/

⇱ How to replace a word inside a string in PHP ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to replace a word inside a string in PHP ?

Last Updated : 15 Jul, 2025

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:

Method 1: Using str_replace() Method

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:


Output
GEEKS for Geeks

Method 2: Using str_ireplace() Method

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:


Output
GEEKS for GEEKS

Method 3: Using preg_replace() Method

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:


Output
geeks for Geeks

Method 4: Using strtr()

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!".


Output
Hello, PHP!

Method 5: Using preg_replace_callback()

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().


Output
I have an APPLE, he has an APPLE, she likes apples.

Method 6: Using substr_replace() Method

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


Output
Hello PHP! PHP is beautiful.
Comment