If you want the antepenultimate piece of the URL:
This solution works with all the examples given in the question:
$pedacos = explode('.',$texto);
echo $pedacos[count($pedacos)-2];
Entries:
$texto = "189-72-5-240.paemt702.dsl.brasiltelecom.net.br";
$texto = "+bbbbbbb2.virtua.com.br";
$texto = "+111.222.22.222.dynamic.adsl.gvt.net.br";
Outputs:
brasiltelecom
virtua
gvt
The problem of using fixed position:
If you have addresses with different suffixes in the list, pre-determined positions can be problematic, as in the following examples:
$texto = "bbbbbbb2.virtua.com.br";
$texto = "www.usp.br";
$texto = "66-97-12-89.datalink.net";
Outputs:
virtua Até aqui tudo bem...
www ... mas neste caso teria que ser "usp"...
66-97-12-89 ... e neste teria que ser datalink !
To solve the problem, follow the ...:
Solution for addresses with multiple suffixes:
To resolve what suffix is and what is the domain name itself, you will need a system with a list of "official" suffixes to see what can and can not be removed from the end of the URL.
Mozilla provides a list of suffixes in link .
This function solves the problem well if you apply the suffixes of interest:
function NomeDoDominio( $dominio ) {
// o array precisa estar ordenado dos maiores para os menores
$sufixos = array( '.com.br', '.net.br', '.org.br', '.com', '.br' );
foreach( $sufixos as $sufixo ) {
if( $sufixo == substr( $dominio , -strlen( $sufixo ) ) ) {
$dominio = substr( $dominio , 0, -strlen( $sufixo ) );
break;
}
}
return substr( strrchr( '.'.$dominio, '.'), 1);
}
See working at IDEONE .
Note: In the case of Brazil, for example, an address can be www.jose.silva.nom.br, to further complicate the situation.