Monday, October 09, 2006

preg_replace(): Error - Delimiter must not be alphanumeric or backslash

preg_replace(): Error - Delimiter must not be alphanumeric or backslash

preg_replace() will output a delimiter error if the "$pattern" does not have a / delimiter or if quotes are used when calling the preg_replace() function itself.

The Error:

$patterns[0] = '/PHP/4.4.4/';
$replacements[0] = "FooBar!";

preg_replace("$patterns",$replacements,"$string[$counter]");

The above will result in the following error:
"preg_replace(): Parameter mismatch, pattern is a string while replacement in an array"


Corrected Version:

// Delimiter is /
// Note: the forward slash after PHP is to be escaped with a backslash
// The i after the / is for case-insensitive matches. This means, you can match lower case words with upper case words and vice-versa

$patterns[0] = '/PHP\/4.4.4/i';
$replacements[0] = "FooBar!";

// Double quotes are to be removed
preg_replace($patterns,$replacements,"$string[$counter]");

No comments: