<?php
// 2026-03-14 to 14/03/2026
echo preg_replace('/(\d{4})-(\d{2})-(\d{2})/', '$3/$2/$1', 'Due: 2026-03-14'), "\n";
// "Lovelace, Ada" to "Ada Lovelace"
echo preg_replace('/^(\w+), (\w+)$/', '$2 $1', 'Lovelace, Ada'), "\n";
// $0 is the whole match: wrap every number in brackets
echo preg_replace('/\d+/', '[$0]', 'Rooms 12 and 305'), "\n";
// ${1} when a digit follows the reference
echo preg_replace('/(\d+)/', '${1}0', 'Multiply 5 and 7 by ten'), "\n";
<?php
$text = 'Call 555-1234 or email me at ana@example.com';
$patterns = ['/\d{3}-\d{4}/', '/\S+@\S+/'];
$replacements = ['[phone]', '[email]'];
echo preg_replace($patterns, $replacements, $text), "\n";
// Only the first match
echo preg_replace('/\d+/', '#', 'a1 b2 c3', 1), "\n";
// Count the replacements
$clean = preg_replace('/\s{2,}/', ' ', 'a b c d', -1, $count);
echo "$clean ($count replacements)\n";
<?php
$price = '$10';
// Wrong: "$10" is read as backreference 10
echo preg_replace('/PRICE/', $price, 'Only PRICE today'), "\n";
// Right: the callback's return value is used as is
echo preg_replace_callback('/PRICE/', fn() => $price, 'Only PRICE today'), "\n";
// Or, for fixed text, no regex at all
echo str_replace('PRICE', $price, 'Only PRICE today'), "\n";