<?php
$result = "" ;
$str = 'vinte cinco reais e vinte cinco centavos' ;
//regex
//Primeiro usa o trim() para limpar os espaços do início e do final da string.
//preg_replace() para remover os espaços duplicados.
//O caracter de escape \s significa "qualquer espaço em branco".
//A notação (?=) é usada para realizar pesquisa adiante. Na prática ele significa "qualquer espaço que é seguido por outro espaço". Isso remove os duplicados, deixando apenas um espaço em branco.
//substitue todos os caracteres " e " por " " na string
//cria array
//itero o array e concateno o caractere "e" quando necessario
for ( $i = 0 ; $i < count ( $a ) ; $i ++ ) {
//interrompe o laço for para evitar o erro Notice: Undefined offset para "$a[$i+1]" caso fosse realizado a ultima iteraçao
$result = $result . $a [ $i ] ;
break ;
}
//concateno o caractere "e" quando necessario
if ( ( $a [ $i + 1 ] == "reais" ) || ( $a [ $i + 1 ] == "mil" ) || ( $a [ $i + 1 ] == "centavos" ) ) {
$result = $result . $a [ $i ] . " " ;
} else {
$result = $result . $a [ $i ] . " e " ;
}
}
echo $result ;
PD9waHAKCgkkcmVzdWx0PSIiOwoJCgkkc3RyID0gJ3ZpbnRlIGNpbmNvIHJlYWlzIGUgdmludGUgY2luY28gY2VudGF2b3MnOyAKCQoJLy9yZWdleAoJLy9QcmltZWlybyB1c2EgbyB0cmltKCkgcGFyYSBsaW1wYXIgb3MgZXNwYcOnb3MgZG8gaW7DrWNpbyBlIGRvIGZpbmFsIGRhIHN0cmluZy4KCS8vcHJlZ19yZXBsYWNlKCkgcGFyYSByZW1vdmVyIG9zIGVzcGHDp29zIGR1cGxpY2Fkb3MuCgkvL08gY2FyYWN0ZXIgZGUgZXNjYXBlIFxzIHNpZ25pZmljYSAicXVhbHF1ZXIgZXNwYcOnbyBlbSBicmFuY28iLgoJLy9BIG5vdGHDp8OjbyAoPz0pIMOpIHVzYWRhIHBhcmEgcmVhbGl6YXIgcGVzcXVpc2EgYWRpYW50ZS4gTmEgcHLDoXRpY2EgZWxlIHNpZ25pZmljYSAicXVhbHF1ZXIgZXNwYcOnbyBxdWUgw6kgc2VndW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