Saturday, October 07, 2006

Find and Replace the Exact Match in a String

To find and replace the exact match in a string, use the function ereg_replace. ereg will find the exact match and not a pattern.

// Strip the extra --
$string= ereg_replace("--","-",$string);
// Replace \n with a br tag
$string = str_replace("\n","
",$string);

// Find and replace multiple needles in a haystack
$patterns[0] = '/>/';
$patterns[1] = '/1/';
$patterns[2] = "/2/";
$patterns[3] = '/3/';
$patterns[4] = '/4/';

// Escape non alpha characters
$patterns[5] = '/\"/';
$patterns[6] = '/\+/';
$patterns[7] = '/\'/';
$patterns[8] = '/\./';
$patterns[9] = '/Some Text/';

$replacements = '-';

$data = preg_replace($patterns, $replacements, $data);

No comments: