SyntaxStudy
Sign Up
PHP Advanced Search & Replace
PHP Intermediate 8 min read

Advanced Search & Replace

Beyond simple str_replace(), PHP offers powerful tools for pattern-based search and multi-value replacement.

  • str_replace() accepts arrays for both search and replace — pairs are processed in order.
  • preg_replace() uses PCRE regular expressions for complex patterns.
  • preg_match() tests a pattern and captures groups.
  • preg_split() splits a string by a regex delimiter.
Example
<?php
// Array find-and-replace
$dirty  = 'colour & flavour';
$search  = ['colour', 'flavour'];
$replace = ['color',  'flavor'];
echo str_replace($search, $replace, $dirty); // color & flavor

// Case-insensitive version
echo str_ireplace('HELLO', 'Hi', 'Hello World'); // Hi World

// Regex replace — strip HTML tags leaving text
$html   = '<p>Hello <strong>World</strong></p>';
$plain  = preg_replace('/<[^>]+>/', '', $html);
echo $plain; // Hello World

// preg_match with capture groups
$date = '2024-07-15';
if (preg_match('/(\d{4})-(\d{2})-(\d{2})/', $date, $m)) {
    echo "Year: {$m[1]}, Month: {$m[2]}, Day: {$m[3]}";
}

// preg_split
$parts = preg_split('/[\s,]+/', 'one, two,  three');
print_r($parts); // ['one', 'two', 'three']
Pro Tip

Tip: Pass a limit as the fourth argument to preg_replace() to restrict how many replacements are made, or use preg_replace_callback() when the replacement value needs to be computed dynamically.