Roman numerals with ucwords () or ucfirst ()

4

While typing this question I modified some things, which made me able to solve the problem. So I'm creating this "share the knowledge" if someone has the same problem.

Suppose the following names:

  • Assassin's Creed III

  • Problem:

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

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

    Result:

  • Assassin's Creed II
  • Assassin's Creed Iv: Black Flag
  • The result is correct for the function.

      

    What I want:

  • Assassin's Creed III
  • Assassin's Creed IV : Black Flag
  • asked by anonymous 30.01.2016 / 16:57

    1 answer

    5

    In order to only keep (or make) the Roman numerals in capital letters I created this, adapting it from some research.

    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.
    ?>
    
      

    Result:

  • Assassin's Creed III
  • Assassin's Creed IV: Black Flag
  •   

    Other tests:

  • grand theft auto v > Grand Theft Auto V
  • final fantasy xv > Final Fantasy XV
  • final Fantasy Xiii > Final Fantasy XIII
  • FINAL FANTASY® XIV: A Realm Reborn > Final Fantasy® XIV: A Realm Reborn
  • Function:

    For those who want to use it 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, ' ');
    }
    

    Use:

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

    Example:

    echo nucword('grand theft auto v');
    // Grand Theft Auto V
    
        
    30.01.2016 / 16:57