Creating SEO friendly URL
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 = transliterator_transliterate('de-ASCII; Any-Latin; Latin-ASCII;', $sString);
$sString = iconv ('utf-8', "ascii//TRANSLIT//ignore", $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
- Explanation of the term "SEO" at wikipedia: https://de.wikipedia.org/wiki/Suchmaschinenoptimierung
- iconv at php.net: http://php.net/manual/de/function.iconv.php
- Unicode Regular Expressions: http://www.regular-expressions.info/unicode.html