facebook icon twitter icon angle down linkedin icon youtube icon
Home > Blog > replace-word-in-php

How to replace word inside a string in PHP

You can use str_replace() function to replace a word from a string. str_replace() is a PHP built-in function.

If you just want to replace a single word, then you can simply do it by providing the exact parameter value. But if you want to replace multiple words at once, you need to call array() function within str_replace() function.

Let’s do it.

Basic syntax

str_replace('substring', 'replaced_string', 'original_string');

We need to provide three parameters for both methods.

1. Substring is the first parameter which should be replaced with replaced_string.

2. Replaced_string will replace the substring.

3. Original_string will contain the full string from where you want to replace word.

In the placement of parameters, you can use PHP variables.

Discussion: Replace word from a string

Lets explore the task practically.

Example 1: Replace just a single word with another one

<?php
//input string
$string = 'I like you. I like you. I like you.';            
//replacing the word
$strings = str_replace( 'like', 'hate', $string );
//showing result
echo $string;
?>

Output:

I hate you. I hate you. I hate you.

Example 2: Replace a single word using preg_replace()

<?php
//input string
$$string = 'I hate my mind. I hate your mind. I hate their mind.';
//defining substring
$sub ='hate';
//replacing the word
$string = preg_replace("/\b$sub\b/i","love",$string);
//showing result
echo $string;
?>

Output:

I love my mind. I love your mind. I love their mind.

Example 3: Replace multiple words from a string

<?php
//input string
$string = 'I like you. I like you. I like you.';
//replacing multiple words using array
$string = str_replace(array('like','you'), array('hate','me'), $string );
//showing result
echo $string;
?>

Output:

I hate me. I hate me. I hate me.

Tarikul islam

About Torikul islam

Torikul islam is a professional web developer and affiliate marketer. Join Torikul to learn how to start a website and operate it well. He started his Web Developement career from Bangladesh Association of Software and Information (BASIS) in 2015. Later he continiued his journey to expanding knowledge and sharing it with others.

Write a Comment

No comment yet