$query = "select a.id_rota, a.tipo_acesso, a.ramal,b.modelo from pbx_rotas_saida_ramais a inner join pbx_rotas_saida_modelos b on a.id_rota = b.id_rota
where ramal = '$ramal'
and '$destino' ~ case when (substring(modelo from '.$') <> '.') then replace('^'||replace(replace(modelo||'$','X','[0-9]'),'Z','[1-9]'),'N','[2-9]')
when (substring(modelo from '.$') = '.') then replace('^'||replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]') end
case when (substring(modelo from '.$') <> '.') then length(replace(replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]'))
when (substring(modelo from '.$') = '.') then length(replace(replace(replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]'),'.',REPEAT('[0-9]', 100))) end as prioridade
from pbx_rotas_saida_ramais a inner join pbx_rotas_saida_modelos b on a.id_rota = b.id_rota
inner join pbx_rotas_saida c on a.id_rota = c.id
where ramal = '$ramal'
and '$destino' ~ case when (substring(modelo from '.$') <> '.') then replace('^'||replace(replace(modelo||'$','X','[0-9]'),'Z','[1-9]'),'N','[2-9]')
when (substring(modelo from '.$') = '.') then replace('^'||replace(replace(modelo,'X','[0-9]'),'Z','[1-9]'),'N','[2-9]') end