3v4l.org

run code in 300+ PHP versions simultaneously
<?php function is_allcaps($string) { $last_letter = mb_substr($string, -1, 1, 'UTF-8'); return $last_letter === mb_strtoupper($last_letter, 'UTF-8'); // otherwise use cytpe_upper() and setlocale() } function plural_to_singular($string) { // quick return of "untouchables" if(preg_match('~^(?:[oó]culos|parab[eé]ns|f[eé]rias)$~iu', $string)) { return $string; } $regex_map = [ '~[õã]es$~iu' => 'ão', '~(?:[áó].*e|[eé])is$~iu' => 'el', '~[^eé]\Kis$~iu' => 'l', '~ns$~iu' => 'm', '~eses$~iu' => 'ês', '~(?:[rzs]\Ke)?s$~iu' => '' ]; foreach ($regex_map as $pattern => $replacement) { $singular = preg_replace($pattern, $replacement, $string, 1, $count); if ($count) { return is_allcaps($string) ? mb_strtoupper($singular) : $singular; } } return $string; } $words = array( 'óculos' => 'óculos', 'papéis' => 'papel', 'anéis' => 'anel', 'PASTEIS' => 'PASTEL', 'CAMIÕES' => 'CAMIÃO', 'rodas' => 'roda', 'cães' => 'cão', 'meses' => 'mês', 'vezes' => 'vez', 'luzes' => 'luz', 'cristais' => 'cristal', 'canções' => 'canção', 'nuvens' => 'nuvem', 'alemães' => 'alemão' ); foreach($words as $plural => $singular) { echo "$plural => $singular = " , plural_to_singular($plural) , "\n"; }
Output for 5.6.40, 7.1.0 - 7.1.33, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.33, 8.2.0 - 8.2.29, 8.3.0 - 8.3.26, 8.4.1 - 8.4.13
óculos => óculos = óculos papéis => papel = papel anéis => anel = anel PASTEIS => PASTEL = PASTEL CAMIÕES => CAMIÃO = CAMIÃO rodas => roda = roda cães => cão = cão meses => mês = mês vezes => vez = vez luzes => luz = luz cristais => cristal = cristal canções => canção = canção nuvens => nuvem = nuvem alemães => alemão = alemão

preferences:
140.2 ms | 408 KiB | 5 Q