I can do this using explode (or have fun with with strrpos), but i prefer to using preg_replace because should be a bit faster, i think (isn’t it?). Plus, it’s concise and elegant.
The purpose is, given a string like a_b_c to obtain another sting where characters following the last _ where substituted with passed string.
I’m not good at regular expression. I’ve to find the time to buy a good book at study. Anyway i’ve tried this regex '/_(.*)$/' as match the end of the string, capture any character following the last underscore.
What’s wrong in my argumentation?
// Do it using explode
function foo($string, $replacement)
{
$pieces = explode('_', $string);
array_pop($pieces);
return implode('_', array_merge($pieces, array($replacement)));
}
// Do it using regular expression (not working)
function bar($string, $replacement)
{
return preg_replace('/_(.*)$/', $replacement, $string);
}
echo foo('a_b_c', 3); // Prints a_b_3
echo bar('a_b_c', 3); // Prints a3 wrong!!!
Depending on your common search string and your version of PCRE, either
preg_replaceorstrrposwill probably fare best:Functions
Test harness
Results
Note that (at least on my set-up with PHP 5.4.0),
preg_replacegivesstrrposa run for its money until there are a large number of underscores preceding the last one.EDIT: I plugged bfrohs’s regex into the suite and unless the underscore to replace is near the beginning of the string, it doesn’t do very well: