PHP remove all occurrences of string except last with preg_replace

While trying to manipulate a string in PHP, I ran into a simple but still challenging (for me), road block trying to remove all instances of “.” and replace with a comma with the exception of the last instance of the period.

It’s easy to select the first occurrence, simply add an integer argument at the end of the function to show how occurrences you want to replace.

$theContent = preg_replace('/\./', ',', $theContent, 1);

Simple! The 1 tells the function I want to replace up to the first occurrence.

Simple, if you know you will 4 occurrences, simple add a 3. However if you are doing this dynamically you need to know how many times the period occurs and subtract 1. So I did this:

$theCount = substr_count($theContent, '.') - 1; // count how many time the period occurs in the string
$theContent = preg_replace('/\./', ',', $theContent, $theCount); // replace all but last one

Great, but it’s still two lines of code for one simple process. So…

$theContent = preg_replace('/\./', ',', $theContent, (substr_count($theContent, '.') - 1));

Bam, done!