Creating SEO friendly URL

2016-03-14 2021-09-19 11:45:51 PHP, SEO, EN

Deutsche Version: String SEO optimieren (creating SEO friendly URL)

This is about how to create a SEO Friendly URL from a string with a PHP Function

The function seofy () below creates a friendly version of a string. Umlauts and other characters not contained in the ASCII character set are either reduced to the basic form equivalent (e. g.: é becomes e and ú becomes u) or completely converted (e. g.: ß becomes ss and ü becomes ue).

This succeeds on the one hand because the php function preg_replace performs the replacement by means of unicode - i. e. Unicode Regular Expressions - and on the other hand because an approximate translation is attempted by means of php function iconv with option TRANSLIT.

Quote php. net about iconv and TRANSLIT:

If you append the character string //TRANSLIT to out_charset, transliteration is activated. This means that a character that cannot be displayed in the target character set can be approximated with one or more similar-looking characters.[…]

Function

<?php 
/**
 * prepares a string optimized for SEO
 * @param string $sString 
 * @return string $sString SEO optimized string
 */
function seofy ($sString = '')
{
    $sString = preg_replace ('/[^\pL\d_]+/u', '-', $sString);
    $sString = trim ($sString, "-");
    $sString = iconv ('utf-8', "us-ascii//TRANSLIT", $sString);
    $sString = strtolower ($sString);
    $sString = preg_replace ('/[^-a-z0-9_]+/', '', $sString);

    return $sString;
}

Examples

<?php 

echo seofy('Straßenfest in München');          // => strassenfest-in-muenchen
echo seofy('José Ignacio López de Arriortúa'); // => jose-ignacio-lopez-de-arriortua

Links


This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".