Search code examples
phpregexurlurl-rewritingslug

Improve converting string to readable urls


The following function rewrites urls from news and product titles that contain all sorts of characters. The string I wish to create consists of only alphanumeric values and "-", but no ending "-" or whitespace and no repeated "-". The below function works fine, but I wondered if there is any way to write it simpler or more efficient?

function urlName($string) {
    $string = trim($string);                          // no open ends
    $string = strtolower($string);                    // all lowercase
    $string = strtr($string, 'äöåÄÖÅ', 'aoaaoa');     // substitute umlauts
    $string = preg_replace('/[\W]+/', '-', $string);  // substitute non-word characters with -
    $string = preg_replace('/^-*|-*$/', '', $string); // no beinging or ending -
    return $string;
}

Solution

  • I think your code can be compacted to this:

    function urlName($string) {
        $patterns = array('/^[\s-]+|[\s-]+$/', '/[\W]+/');
        $replacements = array('', '-');
    
        $string = strtr(strtolower($string), 'äöåÄÖÅ', 'aoaaoa');
        // or you can use:
        // $string = strtr(strtolower($string), $someTrMapping);
    
        return preg_replace($patterns, $replacements, $string);
    }