Skip to content
Related Articles

Related Articles

How to replace a word inside a string in PHP ?

Improve Article
Save Article
  • Last Updated : 03 Jun, 2022
Improve Article
Save Article

Given a string containing some words and the task is to replace all the occurrences of a word within the given string str in PHP. In order to do this task, we have the following methods in PHP:

Method 1: Using str_replace() Method: The str_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:

PHP




<?php
// PHP program to replace all occurrence
// of a word inside a string
   
// Given string
$str = "geeks for Geeks";
 
// Word to be replaced
$w1 = "geeks";
 
//  Replaced by
$w2 = "GEEKS";
   
// Using str_replace() function
// to replace the word
$str = str_replace($w1, $w2, $str);
 
// Printing the result
echo $str;
?>

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:

PHP




<?php
// PHP program to replace
// a word inside a string
   
// Given string
$str = "geeks for Geeks";
 
// Word to be replaced
$w1 = "geeks";
 
//  Replaced by
$w2 = "GEEKS";
   
// Using str_ireplace() function
// replace the word
$str = str_ireplace($w1, $w2, $str);
 
// Printing the result
echo $str;
?>

Output

GEEKS for GEEKS

Method 3: Using preg_replace() Method: The preg_replace() method is used to perform a regular expression for search and replace the content.

Syntax:

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

Example:

PHP




<?php
// PHP program to replace
// a word inside a string
   
// Given string
$str = "geeks for Geeks";
 
// Word to be replaced
$w1 = "geeks";
 
//  Replaced by
$w2 = "GEEKS";
   
// Using preg_replace() function
// to replace the word
 
$str = preg_replace('/bgeeksb/',$w2, $str);
 
// Printing the result
echo $str;
?>

Output

geeks for Geeks

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!