'; // if we know what attribute we need to replace // we need to search and replace the string: $attribute=XXX or $attribute="XXX" // with $attribute=\"$value\" $pattern = '/' . $attribute . '="([^"]+?)"/'; return preg_replace($pattern, $attribute . '="' . $value . '"', $string); }