Fueling Your Coding Mojo

Buckle up, fellow PHP enthusiast! We're loading up the rocket fuel for your coding adventures...

Popular Searches:
288
Q:

Regular expression in php to find roman numerals

Hey everyone,

I'm working on a project in PHP where I need to find and verify Roman numerals within a given text string. I know that Roman numerals can range from the basic ones like I, V, X, L, C, D, M, to more complex ones like IV, IX, XL, XC, CD, CM, and so on.

I've been trying to come up with a regular expression to capture these Roman numerals, but I'm having some trouble. Can anyone help me out with this?

All Replies

mhand

Hey folks,

I stumbled upon this thread and thought I'd share a different approach I used to identify Roman numerals in PHP. Instead of relying on regular expressions, I found it more effective to utilize the `IntlChar` class introduced in PHP 7.

Here's a code snippet to demonstrate how you can leverage the `IntlChar` class to find Roman numerals:

php
function findRomanNumerals($text) {
$result = [];
$textLength = mb_strlen($text, 'UTF-8');

for ($i = 0; $i < $textLength; $i++) {
$currentChar = mb_substr($text, $i, 1, 'UTF-8');
$charCode = IntlChar::ord($currentChar);

if (IntlChar::hasBinaryProperty($charCode, IntlChar::PROPERTY_NUMERIC_TYPE)
&& IntlChar::getIntPropertyValue($charCode, IntlChar::PROPERTY_NUMERIC_TYPE) === IntlChar::DOUBLE_WIDTH)
{
$result[] = $currentChar;
}
}

return $result;
}

$romanNumerals = findRomanNumerals($text);

if (!empty($romanNumerals)) {
// Roman numerals found!
// Process the numerals accordingly
} else {
// No Roman numerals found
}


Using the `IntlChar` class allows you to accurately identify Roman numerals without relying on regular expressions or manually defining patterns. It checks for characters with the DOUBLE_WIDTH property, which effectively captures Roman numerals and excludes other numeric characters.

Give it a try and let me know if it works for you or if you come across any issues. Happy coding!

smitham.kellie

Hey there!

I've had a similar need in one of my previous projects, and I managed to come up with a regular expression that worked well for me. Here's what I used:

php
$pattern = '/^(M{0,3})(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$/';

if (preg_match($pattern, $text)) {
// Roman numeral found!
// Do something with it
} else {
// No Roman numerals found
}


In this regular expression, I've broken down the Roman numerals into their basic components and their possible combinations. The `^` and `$` symbols ensure that the entire text string matches the Roman numeral pattern.

I hope this helps! Let me know if you have any further questions or if there's anything else I can assist you with.

New to LearnPHP.org Community?

Join the community