You might try this. It might make it faster, or not. The strpos() function is very fast compared to str_replace() and the str_replace won't be performed unless it's needed. The overhead of the foreach loop may outweigh the advantage, but it might be worth a try:
<?php
$ca_provinces = array(
"Alberta" => "AB",
"British Columbia" => "BC",
"Manitoba" => "MB",
"New Brunswick" => "NB",
"Newfoundland and Labrador" => "NL",
"Northwest Territories" => "NT",
"Nova Scotia" => "NS",
"Nunavut" => "NU",
"Ontario" => "ON",
"Prince Edward Island" => "PE",
"Quebec" => "QC",
"Saskatchewan" => "SK",
"Yukon" => "YT"
);
$process = false;
foreach($ca_provinces as $long => $short) {
if (strpos($input, $long) !== false {
$process = true;
}
}
if ($process) {
return str_replace(array_keys($ca_provinces), array_values($ca_provinces), $input);
}
return $input;
A *much* faster way, if it's feasible for your use case (probably not), is to do it in a plugin attached to OnDocFormSave. That way it only happens once and doesn't effect page load times at all.
[update] On second thought, since your text is short and (at least with the province placeholder) you know the replace is necessary. My version would probably be slower.