Search code examples
phpurlurl-rewritingurlencodeurl-encoding

URL encoded character replacement with predefined characters


I am trying to fool-proof dynamic generation or url's so that there are no ugly url encoded characters. I generate url's with data from the MySQL database.

For example I have the title field that I generate the url from by replacing spaces with dashes (-).

domain.com/movie/the-terminator/

The issue is that I cannot anticipate all the character that might be in the title. This means that the generated url is not going to match the actual url in the browser bar because it will get encoded.

Is there any php code available that does this replacement? I wouldn't want to do it manually as there are a lot of character to be encoded. I would also like to have few other character replaced such as brackets "(" and ")". The may be a special php method to replace url encoded characters with a defined value, if so please let me know as that may solve my problem very easily, thanks.


Solution

  • check out this link. http://cubiq.org/the-perfect-php-clean-url-generator - "THE PERFECT PHP CLEAN URL GENERATOR"

    example:

    setlocale(LC_ALL, 'en_US.UTF8');
    function toAscii($str, $replace=array(), $delimiter='-') {
        if( !empty($replace) ) {
            $str = str_replace((array)$replace, ' ', $str);
        }
    
        $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
        $clean = preg_replace("/[^a-zA-Z0-9/_|+ -]/", '', $clean);
        $clean = strtolower(trim($clean, '-'));
        $clean = preg_replace("/[/_|+ -]+/", $delimiter, $clean);
    
        return $clean;
    }