Class it:

/**
 * Replace parts of a string matched by a pattern with according replacement string. See convertregex for named parameters.
 * @param $replacementes Array with patterns as keys and replacement strings as values
 * @param $string String to change
 * @param $p['limit'] limit number of replacements (default: all)
 * @return New string
 * @see convertregex for more options in $p
 */
static function replace($replacements, $string, $p = array())
{
    $encoding = ini_get('default_charset') == 'utf-8' ? 'u' : '';
    foreach ($replacements as $pattern => $dummy)
        $patterns[] = !preg_match('/\\\\[wb]|[!\x80-\xff]|\[\[:/i', $pattern) && !$p ? "!$pattern!i$encoding" : it::convertregex($pattern, $p);

    $result = preg_replace($patterns, $replacements, $string, isset($p['limit']) ? $p['limit'] : -1);

     if ($result === null && preg_last_error() == PREG_BAD_UTF8_ERROR)
        it::error("Invalid utf-8 in it::replace haystack: " . substr($string, 0, 500)); # UTF8SAFE

    return $result;
}