How can regular expressions be optimized to accurately remove line breaks at the end of a string in PHP?

To accurately remove line breaks at the end of a string in PHP using regular expressions, you can use the rtrim() function along with a regular expression pattern that matches line breaks (\r\n|\r|\n) at the end of the string. This will ensure that only line breaks at the end of the string are removed, leaving any line breaks within the string intact.

$string = "This is a string with line breaks at the end.\n\n";
$cleanedString = rtrim($string, "\r\n");
echo $cleanedString;