Replacing Text in PHP Strings

Explains how to replace chunks of text inside PHP strings using str_replace() and substr_replace(). Also looks at deleting and inserting text.

As well as searching strings in PHP, often it's useful to replace text within strings too. For example, it can be handy for manipulating strings containing data, or when formatting text for displaying in a Web page.

PHP gives you a couple of useful functions for replacing text in a string:

  • str_replace() searches for one string of text and replaces it with another.
  • substr_replace() replaces text at a specified position within a string.

Read on to discover how to use these 2 useful PHP functions.

Searching and replacing with str_replace()

str_replace() works much like the "replace all" function of a word processor, replacing all occurrences of a chunk of text with a different chunk of text. It takes 3 arguments:

  • The text to search for
  • The text to replace it with
  • The string to search through

str_replace() returns the string with all occurrences of the search text replaced with the replacement text. (The original string is untouched.) For example:


$myString = "'My amiable lady!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable lady?'";
echo str_replace( 'lady', 'wife', $myString );

The above code displays:


'My amiable wife!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable wife?'

Want to know how many replacements were made? Pass a variable as a fourth argument; str_replace() then stores the number of replacements in this variable:


$myString = "'My amiable lady!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable lady?'";
str_replace( 'lady', 'wife', $myString, $num );
echo $num;  // Displays "2"

Searching and replacing many chunks of text at once

You can pass arrays of strings for the first and second arguments to str_replace() to search and replace multiple chunks of text at the same time:


$myString = "'My amiable lady!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable lady?'";
$searchTerms = array ( 'lady', 'amiable' );
$replacements = array ( 'wife', 'lovely' );
echo str_replace( $searchTerms, $replacements, $myString );

The above code displays:


'My lovely wife!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my lovely wife?'

Searching and replacing text in many strings at once

To search and replace text in multiple strings, pass an array of strings to search through as the third argument. str_replace() returns the array of strings with the text replaced:


$string1 = "'and with your amiable lady as the presiding genius over your home and heart--'";
$string2 = "'My amiable lady!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable lady?'";
$myStrings = array ( $string1, $string2 );
$newStrings = str_replace( 'lady', 'wife', $myStrings );
echo $newStrings[0] . "<br />";
echo $newStrings[1] . "<br />";

The above code displays:


'and with your amiable wife as the presiding genius over your home and heart--'
'My amiable wife!' he interrupted, with an almost diabolical sneer on his face. 'Where is she--my amiable wife?'

str_replace() is case sensitive, so "hello" won't match "Hello", for example. If you don't care about matching case, you can use the case-insensitive equivalent function, str_ireplace().

Replacing part of a string with substr_replace()

substr_replace() replaces text at a specified index position in a string. To use it, pass the following arguments:

  • The string to work on
  • The replacement text
  • The index position at which to start the replacement

By default, substr_replace() replaces everything from the start position to the end of the string with the supplied replacement text. For example:


$myString = "Nothing was stirring except a brindled, grey cat";
echo substr_replace( $myString, "moving", 12 );  // Displays "Nothing was moving"

Controlling how many characters to replace

If you'd prefer not to replace everything up to the end of the string, you can specify an optional fourth argument: the number of characters to replace. For example:


$myString = "Nothing was stirring except a brindled, grey cat";
echo substr_replace( $myString, "moving", 12, 8 );  // Displays "Nothing was moving except a brindled, grey cat"

If the fourth argument is negative then substr_replace() replaces up to that many characters from the end of the string:


$myString = "Nothing was stirring except a brindled, grey cat";
echo substr_replace( $myString, "moving", 12, -21 );  // Displays "Nothing was moving a brindled, grey cat"

Deleting text

To delete some text from a string without replacing it with anything, specify an empty string as the second argument:


$myString = "Nothing was stirring except a brindled, grey cat";
echo substr_replace( $myString, "", 29, 10 );  // Displays "Nothing was stirring except a grey cat"

Inserting text

To insert some text without deleting anything, specify zero as the fourth argument:


$myString = "Nothing was stirring except a brindled, grey cat";
echo substr_replace( $myString, "shaggy ", 40, 0 );  // Displays "Nothing was stirring except a brindled, shaggy grey cat"

You've now looked at how to replace text inside PHP strings. You explored str_replace() for searching and replacing text, and substr_replace() for replacing text at a specicied position within a string. Happy coding!

Learn PHP With Ease!

Written by Matt Doyle — ELATED's resident Web programming expert — Beginning PHP 5.3 is a complete introduction to PHP, covering everything in these tutorials and lots more besides. Find out how to:

  • Set up PHP on your computer
  • Use strings, arrays, functions and objects
  • Create interactive Web forms
  • Handle cookies and sessions
  • Work with files on the server
  • Build database-driven sites with MySQL
  • Send emails from your scripts
  • Create images on the fly with PHP
  • Work with regular expressions
  • Write robust, secure PHP applications

...and lots more!

“What a pleasure it's been spending hours and hours studying PHP with this magical book.” — Lulio, Florida
“The book is not only great for learning, but I find myself using it constantly as a reference as well!” — David A. Stoltz

Buy Beginning PHP 5.3 now from Amazon.comBeginning PHP 5.3 or Amazon.co.ukBeginning PHP 5.3.

Follow Elated

Related articles

Responses to this article

There are no responses yet.

Post a response

Want to add a comment, or ask a question about this article? Post a response.

To post responses you need to be a member. Not a member yet? Signing up is free, easy and only takes a minute. Sign up now.

Top of Page