I am dealing with a relatively inconsistent and messy data source, and need some help with a very specific regular expression.
A lot of the strings we get are prepended with 2 letter alphanumeric (upper or lower cases) followed by a space, that we need to purge, so we can do something like the following:
$town = "PE Springfield" // truncate to "Springfield"
$town = "Kr Nashville" // truncate to "Nashville"
But in some cases the prefixes are directives such as NE, Sw etc. which we need to keep.
$town = "NW Brockvillle" // keep to "NW Brockville"
$town = "Se Nashville" // uppercase to " SE Nashville"
I could write a more complex series of if/else statements to process the direction strings separately then merge it back, but I'm hoping there is a brilliant regular expression.
The regex I have so far for NW/NE matching (all cases) or any 2 alphanumeric opening followed by space is:
$cleanpattern[] = '/^[Nn][Ww]\s/';
$cleanpattern[] = '/^[Nn][Ee]\s/';
$cleanpattern[] = '/^[Ss][Ww]\s/';
$cleanpattern[] = '/^[Ss][Ee]\s/';
$cleanpattern[] = '/^[A-Za-z]{2}\s/';
Note that by some grace, this data source never supplies just N, S, E or W (single letter). But I suppose it doesn't hurt to cover that just in case for future?
Then for replacement strings, I have the following array (whether the Sw/ne comes in lower or upper, I want them all uppercase):
$replacementpattern[] = 'NW ';
$replacementpattern[] = 'NE ';
$replacementpattern[] = 'SW ';
$replacementpattern[] = 'SE ';
$replacementpattern[] = '';
When I run the preg_replace($cleanpattern, $replacementpattern, $town, 1) the problem is that after the NW/SE etc. are checked and set, they are then purged by the 5th rule. Turns out the 4th parameter of "LIMIT" on this function doesn't limit the loop within the pattern/replace arrays, but rather only how many replacements are done within each string.