| This php based script will find numbers and give them a cardinal ending. This can be useful for displaying rankings or results of a competition. The script is easy to install and use <?php
function addOrdinalSuffix($number) {
// Determine the last digit of the number
$lastDigit = $number % 10;
$lastTwoDigits = $number % 100;
// Determine suffix based on the number's last digit and last two digits
if ($lastTwoDigits >= 11 && $lastTwoDigits <= 13) {
$suffix = 'th';
} else {
switch ($lastDigit) {
case 1:
$suffix = 'st';
break;
case 2:
$suffix = 'nd';
break;
case 3:
$suffix = 'rd';
break;
default:
$suffix = 'th';
break;
}
}
return $number . $suffix;
}
function findAndConvertNumbers($text) {
// Use regex to find all numbers in the text
$pattern = '/\b\d+\b/';
$convertedText = preg_replace_callback($pattern, function($matches) {
return addOrdinalSuffix($matches[0]);
}, $text);
return $convertedText;
}
// Example usage
$text = "I was born on the 5 of May. It was the 21 century.";
echo findAndConvertNumbers($text);
?>
Explanation:
addOrdinalSuffix($number): This function adds the appropriate ordinal suffix based on the last digit(s) of the number. It handles special cases like numbers ending in "11", "12", or "13".findAndConvertNumbers($text): This function uses a regular expression to find all standalone numbers in a text string. It then applies addOrdinalSuffix to each found number.
Example Output: For the input text: plaintext Copy code "I was born on the 5 of May. It was the 21 century."
The output would be: plaintext Copy code "I was born on the 5th of May. It was the 21st century." |