I have a column of address data that has ordinals displayed like this:
3Rd Floor, Cumbrian House
Room 223, 2Nd Floor
when I would like them to be displayed like this instead:
3rd Floor, Cumbrian House
Room 223, 2nd Floor
I'm trying to make use of the preg_replace function to swap out a capitalised letter, that directly follows a number, with a lower case letter instead. (I admit this is my first time using the preg_replace function. I am however fine with preg_match and regular expressions).
So far I have:
$string = '3Rd Floor, Cumbrian House';
$ordinalregex = '/(^.*\d+)([A-Z])/';
$correctordinal = '$1'.strtolower('$2');
echo preg_replace($ordinalregex,$correctordinal,$string)."<br>";
But its not having the desired effect and outputs the line exactly as it first appeared.
Thanks
I think you need to use preg_replace_callback as I'm not sure you can replace based on the part you matches in normal preg_replace. What you need to do is use a callback function that takes the matches array and processes it (you could also just use preg_match and then work with the matches seperetaly).
This example works (although it uses an anonymous function for the callback, which requires PHP 5.3.0+):
function fixOrdinals($string) {
return preg_replace_callback("/[0-9][A-Z]/",
function ($matches) {
return strtolower($matches[0]);
},
$string
);
}
echo fixOrdinals("3Rd Floor, Cumbrian House")."
";
echo fixOrdinals("Room 223, 2Nd Floor")."
";
echo fixOrdinals("4Th Room, 2Nd Floor")."
";
Output:
3rd Floor, Cumbrian House
Room 223, 2nd Floor
4th Room, 2nd Floor
<?php
$ordinalregex = '/(\d+)(st|nd|rd|th)/ei';
$input = "Room 223, 2Nd Floor";
$input = preg_replace($ordinalregex, "strtolower('$1$2')", $input);
print($input);
The /e modifier tells the interpreter to use eval. Now this works, however it's NOT SECURE. If your input has a \0 (null char) due to a C bug the interpreter will execute the part of the sting after the \0.