How to Replace a Word Inside a PHP String

Sometimes, it is necessary to replace a given word inside a string in PHP. Here, we will consider the main methods that help to carry out the task.

Using str_replace()

The str_replace() function is used for replacing all the occurences of a word 1 by replacing word 2 in a particular string.

The syntax of str_replace() is the following:

str_replace( $searchVal, $replaceVal, $subjectVal, $count )

For a better perception, take a look at the example below:

<?php
// PHP program for replacing all the occurences
// of a word within a string

// Given string
$str = "w3docs is W3docs";

// Word to be replaced
$w1 = "w3docs";

// Replaced by
$w2 = "W3DOCS";

// Using str_replace() function
// for replacing the word
$str = str_replace($w1, $w2, $str);

// Printing the result
echo $str;

?>

Using str_ireplace()

The str_ireplace() function is also aimed at replacing all the occurrences of word 1 by replacing word 2 in a particular string.

Although the aim of str_ireplace() and str_replace() is the same, there is a notable difference: str_ireplace() is considered case-insensitive.

The syntax of str_ireplace is as follows:

str_ireplace( $searchVal, $replaceVal, $subjectVal, $count )

Now, have a look at an example:

<?php
// PHP program to replace
// a word inside a string

// Given string
$str = "w3docs is W3docs";

// Word to be replaced
$w1 = "w3docs";

// Replaced by
$w2 = "W3DOCS";

// Using str_ireplace() function
// replacing the word
$str = str_ireplace($w1, $w2, $str);

// Printing the result
echo $str;

?>

Using preg_replace

This function is applied for performing a regex for search, replacing the content.

The syntax will look as follows:

preg_replace( $pattern, $replacement, $subject, $limit, $count )

Here is a full example:

<?php
// PHP program for replacing
// a word within a string

// Given string
$str = "geeks is W3docs Somegeeks";

// Replaced by
$w2 = "W3DOCS";

// Use preg_replace() function
// for replacing the word `geeks` with `W3DOCS`

$str = preg_replace('/geeks/', $w2, $str);

// Print the result
echo $str;

?>

Note that in all the above examples the string will be replaced even if it is a substring and not a separate word. It is possible to replace only the whole word by using preg_replace.

<?php
// PHP program for replacing
// a word within a string

// Given string
$str = "geeks is W3docs Somegeeks";

// Replaced by
$w2 = "W3DOCS";

// Use preg_replace() function
// for replacing the word `geeks` with `W3DOCS`

$str = preg_replace('/\bgeeks\b/', $w2, $str);

// Print the result
echo $str;

?>
W3DOCS is W3docs Somegeeks