preg_replace php code example

Example 1: php str_replace

<?php
//str_replace("Original Value", "Value to be replaced", "String");
$result = str_replace("1", "2", "This is number 1");
// Output: This is number 2
?>

Example 2: preg_replace

<?php
$string = 'April 15, 2003';
$pattern = '/(\w+) (\d+), (\d+)/i';
$replacement = '${1}1,$3';
echo preg_replace($pattern, $replacement, $string);

Example 3: php preg replace

preg_replace($pattern, $replacement, $subject [, $limit [, &$count]]);
// Returns an array if the subject parameter is an array,
// or a string otherwise.
// If matches are found, the new subject will be returned, otherwise
// subject will be returned unchanged or NULL if an error occurred.

Example 4: 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 5: preg_replace examples

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

Example 6: php preg_replace function

preg_replace($pattern, $replacement, $string);

Tags: