preg_replace examples

Example 1: preg_replace examples

$result = preg_replace('/abc/', 'def', $string);   # Replace all 'abc' with 'def'
$result = preg_replace('/abc/i', 'def', $string);  # Replace with case insensitive matching
$result = preg_replace('/\s+/', '', $string);      # Strip all whitespaces

Example 2: preg_replace examples

$result = preg_replace('/abc(def)hij/', '/\\1/', $string);
$result = preg_replace('/abc(def)hij/', '/$1/', $string);
$result = preg_replace('/abc(def)hij/', '/${1}/', $string);

Example 3: preg_replace examples

$result = preg_replace(
    array('/pattern1/', '/pattern2/'),
    array('replace1', 'replace2'),
    $string
);

Example 4: preg_replace examples

# Strip HTML tag
$result = preg_replace('#<span id="15">.*</span>#m', '', $string);