Problem with function that generates friendly url

0

Good

I have a function that generates the name for friendly urls but I am having a problem that when the function generates the name if that name contains accents it does not put the same word but without accent it puts another character

Function

function url_amigavel($string) {
        $palavra = strtr($string, "ŠŒŽšœžŸ¥µÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ", "SOZsozYYuAAAAAAACEEEEIIIIDNOOOOOOUUUUYsaaaaaaaceeeeiiiionoooooouuuuyy");
        $palavranova = str_replace("_", " ", $palavra);
        $pattern = '|[^a-zA-Z0-9\-]|';    $palavranova = preg_replace($pattern, ' ', $palavranova);
        $string = str_replace(' ', '-', $palavranova);
        $string = str_replace('---', '-', $string);
        $string = str_replace('--', '-', $string);
        return strtolower($string);
    }

For example

César Sousa

Should convert to cesar-sousa But it is to convert like this c-sar-sousa

    
asked by anonymous 14.02.2015 / 19:15

2 answers

4

To clean up anything you want to put into a URL you can use the following function (which uses iconv ):

function sanitize_title($title) {
    // substitui espaços por "-"
    $title = preg_replace('#\s+#', '-', $title);

    // faz a transliteração pra ASCII
    $title = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $title);

    // remove qualquer outra coisa inválida da url
    $title = preg_replace('#[^a-zA-Z0-9_-]+#', '', $title);

    return $title;
}

Before calling this function, you should use setlocale for transliteration to work correctly :

setlocale(LC_ALL, 'pt_BR.UTF-8');

Example:     echo sanitize_title ('César Sousa');     echo sanitize_title ('aéíóú @ # _ 888999-test other words');

Generates:

cesar-sousa
aeiou_888999-teste-outras-palavras

See an Idea Test

    
14.02.2015 / 19:57
0

A simple function that works with me:

function url_amigavel($string){
    return preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($string));
}

Something more complete would be:

function url_amigavel($string){
    $url = str_replace(' ', '_', $string);
    $url = preg_replace("/&([a-z])[a-z]+;/i", "$1", htmlentities($url));

    return strtolower($url);
}

See the test here:

I hope it works

Abs

    
14.02.2015 / 19:28