If you want the penultimate chunk of the URL:
This solution works with all the examples given in the question:
$pedacos = explode('.',$texto);
echo $pedacos[count($pedacos)-2];
Entrances:
$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";
Exits:
brasiltelecom
virtua
gvt
The problem of using fixed position:
If you have addresses with different suffixes in the list, predetermined positions can give problem, as in the following examples:
$texto = "bbbbbbb2.virtua.com.br";
$texto = "www.usp.br";
$texto = "66-97-12-89.datalink.net";
Exits:
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 follows the ...:
Solution for addresses with multiple suffixes:
To resolve what is suffix and what is the domain name itself, you will need a system with an "official" suffix list to query what can and cannot be removed from the end of the URL.
Mozilla provides a list of suffixes in https://publicsuffix.org/.
This function solves the problem well, if suffixes of interest are applied:
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 on IDEONE.
Note: in the case of Brazil, for example, an address may be www.jose.silva.nom.br, to further complicate the situation.
You always want to take the domain name out, is that it? Do you have a fixed list of hosts? You have a list of TLD scopes, that is, it’s always
.net.br
?– bfavaretto