Codectionary / Developer documentation / PHP

PHP pattern-based replacements

preg_replace replaces matches throughout a string and can report how many replacements occurred. It returns null when the regular expression fails.

Syntax

preg_replace($pattern, $replacement, $subject, -1, $count)

Examples

PHP pattern-based replacements

Run as a PHP 8.0+ CLI script, for example php example.php. The multibyte example additionally requires mbstring.

<?php
$count = 0;
$clean = preg_replace('/[ \t]+/', ' ', "Ada   writes\tPHP", -1, $count);
if ($clean === null) throw new RuntimeException(preg_last_error_msg());
echo $clean, PHP_EOL;
echo $count, PHP_EOL;
  1. Output: Ada writes PHP, then 2. Each run of spaces or tabs becomes one space; newlines are unaffected.

Best practices

  • Use str_replace for literal replacements and check for null. Use preg_replace_callback for computed replacements rather than embedding executable text.

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