Kategoriler
Kodlama

Türkçe Slugify URL

PHP ve JavaScript ile metinleri uygun URL formatına çevirmek için fonksiyonlar.

Normalde bir URL’in içerdiği non-latin ve geçersiz karakterleri WordPress’in remove_accents() fonksiyonu ile temizleyebilirsiniz, ve URL şekline çevirebilirsiniz fakat WordPress dışında kullanılabilecek basit bir hem PHP hem de JavaScript fonksiyonu da burada paylaşıp kaydetmiş olayım.

PHP

Öncelikle fonksiyonun doğru çalışabilmesi için stringe mutlaka utf8_decode ve urldecode() yapın. Ve bu sadece Türkçe için, her dili destekleyen biçimler için https://stackoverflow.com/questions/2955251/php-function-to-make-slug-url-string da paylaşılanları deneyebilirsiniz veya WordPress’in fonksiyonunu kopyalayıp kullanabilirsiniz.

Fonksiyon:

// Slugify a string
function Slugify_URL($text){
$text = str_replace('ü','u',$text);
$text = str_replace('Ü','U',$text);
$text = str_replace('ğ','g',$text);
$text = str_replace('Ğ','G',$text);
$text = str_replace('ş','s',$text);
$text = str_replace('Ş','S',$text);
$text = str_replace('ç','c',$text);
$text = str_replace('Ç','C',$text);
$text = str_replace('ö','o',$text);
$text = str_replace('Ö','O',$text);
$text = str_replace('ı','i',$text);
$text = str_replace('İ','I',$text);
        // Strip html tags
$text=strip_tags($text);
        // Replace non letter or digits by -
$text = preg_replace('~[^\pL\d]+~u', '', $text);
        // Remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
        // Lowercase
$text = mb_strtolower($text);
        // Check if it is empty
if (empty($text)){return 'wolkanca';}
        // Return result
return $text;
}

Kullanım örnek:

$benimmetnim = 'Gerçeği konuşmaktan korkmayınız.';
$benimmetnim_D = utf8_decode(urldecode($benimmetnim));
$benimURL = Slugify_URL($benimmetnim_D);
// Çıktı: gercegi-konusmaktan-korkmayiniz

https://slugify.online/ sitesinde denemeler yapabilirsiniz ayrıca daha fazla ihtiyaçlarınızı karşılaması için https://github.com/cocur/slugify de kullanabilirsiniz.

WordPress: sanitize_title; developer.wordpress.org/reference/functions/sanitize_title/, remove_accents; developer.wordpress.org/reference/functions/remove_accents/

JavaScript

Bunun birçok değişik fonksiyonları var ancak en basit ve kolayı TR uyumlusu bu şekilde:

Fonksiyon:

function Slugify_URL(text){
  var trMap ={
    çÇ: "c",
    ğĞ: "g",
    şŞ: "s",
    üÜ: "u",
    ıİ: "i",
    öÖ: "o"
 };
  for (var key in trMap){
    text = text.replace(new RegExp("[" + key + "]", "g"), trMap[key]);
 }
  return text
    .normalize("NFD")
    .trim()
    .replace(/\s/gi, "-")
    .replace(/[^\w\-]+/g, "")
    .toLowerCase();
}

Kullanım örnek:

var metin = "Gerçeği konuşmaktan korkmayınız.";
var adres = Slugify_URL(metin);
console.log("uRl: " + metin);
console.log("adres: " + adres);

Test: