Uppercase Roman numerals with ucwords() or ucfirst()

Asked

Viewed 192 times

4

While typing this question I modified some things, which made me able to solve the problem. That’s why I’m creating this "share the knowledge" in case someone has the same problem.

Suppose the following names:

  1. Assassin’s Creed III

  2. ASSASSIN’S CREED IV: BLACK FLAG

Problem:

To make it standard (and reduce space, because uppercase letters are larger when displayed), I use this:

$nome = ucwords( strtolower( $fonte['Nome'] ) );

Upshot:

  1. Assassin’s Creed Ill
  2. Assassin’s Creed Iv: Black Flag

The result is correct for the function.

What I desire:

  1. Assassin’s Creed III
  2. Assassin’s Creed IV: Black Flag

1 answer

5


In order to be able to only maintain (or make) the Roman numerals in uppercase I created this, adapting from some researches.

Solution:

<?php
$explodes = explode(' ', strtolower( $fonte['Nome'] ) );
// Isso irá forçar tudo para minusculo, afim de entrar no regex e quebrar os espaços.

foreach($explodes as $explode){
// Cria loop finito para cada palavra

   if(!preg_match("/^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})(.?)$/", $explode)){
        $palavra .= ucfirst($explode).' ';
        // Se não houver número romano a primeira letra é passada para maiúsculo.
   }else{
        $palavra .= strtoupper($explode).' ';
       // Se houver número romano tudo é passado para maiúsculo.
   }

}

echo rtrim($palavra, ' ');
// Remove ultimo espaço inserido e exibe.
?>

Upshot:

  1. Assassin’s Creed III
  2. Assassin’s Creed IV: Black Flag

Too many tests:

  1. grand theft auto v > Grand Theft Auto V
  2. final fantasy xv > Final Fantasy XV
  3. final Fantasy Xiii > Final Fantasy XIII
  4. FINAL FANTASY® XIV: A Realm Reborn > Final Fantasy® XIV: A Realm Reborn

Function:

For those who want to use easier:

function nucword($frase){   
$explodes = explode(' ', strtolower($frase) );
$palavra = '';

foreach($explodes as $explode){ 
   if(!preg_match("/^m{0,4}(cm|cd|d?c{0,3})(xc|xl|l?x{0,3})(ix|iv|v?i{0,3})(.?)$/", $explode)){
        $palavra .= ucfirst($explode).' ';
   }else{
        $palavra .= strtoupper($explode).' ';
   }    
}

return rtrim($palavra, ' ');
}

Utilize:

nucword('sua frase Ii');
// Sua Frase II

Example:

echo nucword('grand theft auto v');
// Grand Theft Auto V
  • 1

    There is a lot of poorly used Regex on the site, but for this answer, Regex serves very well. This is a good example of the proper complexity to justify the use.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.