How can PHP developers efficiently handle cases where the "#" symbol needs to be added only before the last number in a string?

PHP developers can efficiently handle cases where the "#" symbol needs to be added only before the last number in a string by using regular expressions. They can use the preg_replace function to find the last number in the string and then add the "#" symbol before it. This approach allows for a flexible and scalable solution to this specific requirement.

$string = "This is an example string with numbers 1234567";
$pattern = '/(\d+)(?!.*\d)/';
$replacement = '#$1';
$newString = preg_replace($pattern, $replacement, $string);

echo $newString;