I need to capitalise acronyms in some text.
I currently have this regex to match on the acronyms:
/(^|[^a-z0-9])(ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI)($|[^a-z0-9])/ig
Explanation: this is aiming to match any of the acronyms where they are either at the start or end of the text, or there isn't a letter or number either side of them (as then they might be part of a word - e.g. I wouldn't want to replace the "Esc" in the word "Escape").
This works most of the time, but doesn't work for the following example:
"abs/esc"
It matches the abs
, but not the esc
. I'm guessing this is because the matches overlap, in that the forward slash is part of the match relating to abs
.
Can anyone suggest how to get a match on both?
As a side note, I'm using PHPs preg_replace_callback to perform the transformation afterwards:
$name = 'abs/esc';
$name = preg_replace_callback('/(^|[^a-z0-9])('ECU|HVAC|ABS|ESC|EGR|ADAS|HEV|HMI')($|[^a-z0-9])/i', function($matches) {
return $matches[1] . strtoupper($matches[2]) . $matches[3];
}, $name);
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…