protected function limitConsecutiveNewlines($string, $limit = 2)
    {
        // Pattern that finds any consecutive newlines that exceed the allowed limit.
        $exceeded = $limit + 1;
        $pattern = '/((\\n){' . $exceeded . ',})/';

        // Create a string with the maximum number of allowed newlines.
        $newlines = '';
        for ($i = 0; $i < $limit; $i++) {
            $newlines .= PHP_EOL;
        }

        // Find each match and replace it with the maximum number of newlines.
        return preg_replace($pattern, $newlines, $string);
    }