Quick actions

cmd+k|ctrl+k

Navigation

Languages

Slug function and automatic id generator for h2 tags

Snippet info

Language

Php

Visibility

public

Author

mertskaplan

Created

2018-09-06T19:48:56Z

Updated

2018-09-06T19:51:33Z

<?php

function slug($str) {
    $search = array('I','İ','ı','ö','Ö','ç','Ç','ğ','Ğ','ü','Ü','Ș','â','Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', 'Â', 'Ă', 'ë', 'Ë');
    $replace = array('i','i','i','o','o','c','c','g','g','u','u','s','a','t', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'e');
    $str = str_ireplace($search, $replace, strtolower(trim($str)));
    $str = preg_replace('/[^\w\d\-\ ]/', '', $str);
    $str = str_replace(' ', '-', $str);
    return preg_replace('/\-{2,}/', '-', $str);
}

$text = '<h2>Instalation</h2><i>sdfsd</i><h2 class="class" id="7y7- ç" type="54">asdİçd</h2>';

function h2slug($text) {
    preg_match_all("|<h2(.*)>(.*)</[^>]+>|U", $text, $out, PREG_SET_ORDER);
    foreach ($out as $header) {
        $slug = slug($header[2]);
        $header[1] = preg_replace('/(?<!\S\W\w\s)(\s?)id(\s?)="(\w*\W*)"/', '' , $header[1]);
        $text = str_replace($header[0], '<h2 id="'. $slug .'"'. $header[1] .'>'. $header[2] .'</h2>', $text);
    }
    return $text;
}
    
echo h2slug($text);
INFO