From time to time I’ll have a string in my project which is simply an acronym (ie. initials) that needs to have all its letters in uppercase form.
eg.
str_replace("Mcg","MCG",$string);
This does the job fine. However, sometimes this string will contain an acronym that is also the start of a word.
eg.
str_replace("Wa","WA",$string)
This will obviously change words like “want” into “WAnt” which I obviously don’t want. Is there some way I can only change words of 2 or 3 characters? I was thinking about exploding the string into an array and going from there. Or is there an easier function I should be utilising?
Use a regex that stops on word boundaries, i.e. something like this:
This replaces all occurrences of ‘Wa’ with ‘WA’, as long as there are spaces, commas, dots, newlines or no characters at all left or right of it (and I’m sure I’m missing a few characters there).
This is better than filtering on whitespace (or spaces), since you might have the following cases: