sábado, 2 de abril de 2011

Slugify em PHP

Quase todas as frameworks utilizadas em PHP têm um método que limpa as variáveis para a criação de URL de forma dinâmica. Para quem precisar de funções equivalentes, fora de uma framework ficam aqui 2 possíveis soluções:


Solução 1 - Substitui os caracteres especiais pelos correspondentes:

function slugify($string) {
    $string = utf8_decode($string);
    $string = html_entity_decode($string);

    $a = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ';
    $b = 'AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn';
    $string = strtr($string, utf8_decode($a), $b);

    $ponctu = array("?", ".", "!", ",");
    $string = str_replace($ponctu, "", $string);

    $string = trim($string);
    $string = preg_replace('/([^a-z0-9]+)/i', '-', $string);
    $string = strtolower($string);

    if (empty($string))
        return 'n-a';

    return utf8_encode($string);
}


Solução 2 - Remove os caracteres especiais:

function slugifyRemove($text) {
    $text = preg_replace('~[^\\pL\d]+~u', '-', $text);
    $text = trim($text, '-');

    if (function_exists('iconv')) {
        $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
    }

    $text = strtolower($text);
    $text = preg_replace('~[^-\w]+~', '', $text);

    if (empty($text)) {
        return 'n-a';
    }

    return $text;
}

Resultados:

$str = "Escolha uma das opções";
echo "slugify: ".slugifyReplace($str);
echo "slugifyRemove: ".slugifyRemove($str);

slugify: escolha-uma-das-opcoes
slugifyRemove: escolha-uma-das-opes

Sem comentários:

Enviar um comentário