Looking for somewhere to host your site? Browse our PHP web hosts section!

Home > Code Snippets > Find and replace words in a text string using str_replace

Find and replace words in a text string using str_replace

Description

This will run through a section of text and change all occurrences of a word into something else using the PHP str_replace function.

The code


<?php


// The text string
$text "The quick brown fox jumped over the lazy dog.";

// The word we want to replace
$oldWord "brown";

// The new word we want in place of the old one
$newWord "blue";

// Run through the text and replaces all occurrences of $oldText
$text str_replace($oldWord $newWord $text);

// Display the new text
echo $text;

?>

Get the code

Download the file to your computer: Click here to get the file