[Previous] [Contents] [Next]

Replacing Characters and Substrings

PHP provides several simple functions that can replace specific substrings or characters in a string with other strings or characters. In the next section we discuss powerful tools for finding and replacing complex patterns of characters. The functions described in this section, however, are more efficient than regular expressions and are often the better choice when searching and replacing strings.

Replacing substrings

The substr_replace( ) function replaces a substring identified by an index with a replacement string:

string substr_replace(string source, string replace, int start [, int length])

Returns a copy of the source string with the characters from the position start to the end of the string replaced with the replace string. If the optional length is supplied, only length characters are replaced. The following examples show how substr_replace( ) works:

$var = "abcdefghij";
// prints "abcDEF";
echo substr_replace($var, "DEF", 3);
// prints "abcDEFghij";
echo substr_replace($var, "DEF", 3, 3);
// prints "abcDEFdefghij";
echo substr_replace($var, "DEF", 3, 0);

The str_replace( ) function returns a string created by replacing occurrences of the string search in subject with the string replace:

mixed str_replace(mixed search, mixed replace, mixed subject)

In the following example, the subject string, "old-age for the old", is printed with both occurrences of old replaced with new:

$var = "old-age for the old.";
echo str_replace("old", "new", $var);

The result is:

new-age for the new.

Since PHP Version 4.0.5, str_replace( ) allows an array of search strings and a corresponding array of replacement strings to be passed as parameters. The following example shows how the fields in a very short form letter can be populated:

// A short form-letter for an overdue account
$letter = "Dear #title #name, You owe us $#amount.";
// Set-up an array of three search strings that
// will be replaced in the form-letter
$fields = array("#title", "#name", "#amount");
// An array of debtors. Each element is an array that
// holds the replacement values for the form-letter
$debtors = array(
    array("Mr", "Cartwright", "146.00"),
    array("Ms", "Yates", "1,662.00"),
    array("Dr", "Smith", "84.75"));
foreach($debtors as $debtor)
  echo "<p>" . str_replace($fields, $debtor, $letter);

The output of this script is as follows:

Dear Mr Cartwright, You owe us $146.00.
Dear Ms Yates, You owe us $1,662.00.
Dear Dr Smith, You owe us $84.75.

If the array of replacement strings is shorter than the array of search strings, the unmatched search strings are replaced with empty strings.

[Previous] [Contents] [Next]