Codectionary / Developer documentation / PHP

Replace Literal Text with str_replace

Substitute fixed substrings, count replacements and recognise sequential replacement effects.

What it is and why to use it

Use str_replace() when the text to replace is a fixed sequence, such as a document marker or a changed product name. It replaces all case-sensitive occurrences and returns a new string. Regular expressions are unnecessary for a literal replacement and make simple tasks harder to read.

How it works

Supply the search text, replacement text and original subject in that order. An optional fourth variable receives the number of replacements. Arrays of search and replacement strings are processed sequentially, meaning text inserted by an earlier replacement can be changed by a later one. strtr with a replacement map is useful when tokens should be replaced without this repeated processing.

Common mistakes and limitations

Replacing a few characters is not general input sanitisation. Escape output for its destination and validate data separately. Do not assume array replacements happen simultaneously. Use preg_replace only when actual pattern matching is needed, and understand that an empty replacement deliberately removes matching text.

Run the examples locally

Save each complete example in its own example.php file and run php example.php in a terminal from that folder. Each example is independent: do not paste both into one file, especially when they declare classes with the same names. Output appears in the terminal. The examples use PHP 8.0-compatible syntax; use a currently supported PHP release for development.

The <?php opening tag starts PHP code. declare(strict_types=1) requests strict scalar argument checks for function calls made from this file; it does not validate external input for you. echo writes output, and PHP_EOL adds the platform’s line ending. Quotation marks delimit strings; they are not part of the printed text unless explicitly included in the string.

These examples use built-in PHP language features and standard extensions. They need no Composer packages, database server, browser APIs or network access. Codectionary’s PHP preview does not execute PHP; use your local interpreter to reproduce the output.

Check your interpreter, lint and run one saved example

php -v
php -l example.php
php example.php

Continue learning

Use the related guides to connect this operation to the surrounding language features. Practise by changing the example inputs and predicting the output before running it.

Syntax

$updated = str_replace($search, $replacement, $subject, $count);

Examples

Update repeated markers

Replace each occurrence and display the replacement count.

<?php
declare(strict_types=1);

$draft = 'Read [topic], then practise [topic].';
$updated = str_replace('[topic]', 'arrays', $draft, $count);
echo $updated, PHP_EOL;
echo $count, ' replacements', PHP_EOL;
  1. The literal marker [topic] occurs twice and both occurrences are replaced.
  2. The fourth argument is written by the function and becomes the integer 2.
  3. The original draft is unchanged. This can support trusted document templates; inserted user text still needs escaping if the final destination is HTML.
  4. Expected output: Read arrays, then practise arrays. 2 replacements

See sequential replacements

Contrast a sequence of replacements with a one-pass token map.

<?php
declare(strict_types=1);

$text = 'A';
echo str_replace(['A', 'B'], ['B', 'C'], $text), PHP_EOL;
echo strtr($text, ['A' => 'B', 'B' => 'C']), PHP_EOL;
  1. str_replace changes A to B first and then changes that new B to C.
  2. The map form of strtr replaces the original A with B without processing the replacement again.
  3. The distinction matters when placeholder values resemble other placeholders. Pick a token strategy that cannot accidentally cascade.
  4. Expected output: C B

Best practices

  • Choose literal replacement for fixed text.
  • Test overlapping replacement rules before applying them to real content.

Runtime & versions

PHP runtime on a server or CLI. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

PHP Manual

Specifications & further reading