Last active
August 21, 2020 06:38
-
-
Save helart/24967533211c6a7f4ef30727328fe6b7 to your computer and use it in GitHub Desktop.
Транслит для URL
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function translit_path($value) | |
{ | |
$converter = array( | |
'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', | |
'е' => 'e', 'ё' => 'e', 'ж' => 'zh', 'з' => 'z', 'и' => 'i', | |
'й' => 'y', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', | |
'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', | |
'у' => 'u', 'ф' => 'f', 'х' => 'h', 'ц' => 'c', 'ч' => 'ch', | |
'ш' => 'sh', 'щ' => 'sch', 'ь' => '', 'ы' => 'y', 'ъ' => '', | |
'э' => 'e', 'ю' => 'yu', 'я' => 'ya', | |
); | |
$value = mb_strtolower($value); | |
$value = strtr($value, $converter); | |
$value = mb_ereg_replace('[^-0-9a-z\.]', '-', $value); | |
$value = mb_ereg_replace('[-]+', '-', $value); | |
$value = trim($value, '-'); | |
return $value; | |
} | |
function traslit_url($url) | |
{ | |
$url = parse_url(trim($url)); | |
if (!empty($url['host'])) { | |
$res = ''; | |
if (!empty($url['scheme'])) { | |
$res .= $url['scheme'] . '://'; | |
} | |
if (!empty($url['host'])) { | |
$res .= idn_to_ascii($url['host']); | |
} | |
if (!empty($url['port'])) { | |
$res .= ':' . $url['port']; | |
} | |
if (!empty($url['path'])) { | |
$path = explode('/', $url['path']); | |
foreach ($path as $i => $row) { | |
if (preg_match('/[а-яё]/iu', $row)) { | |
$path[$i] = translit_path($row); | |
} | |
} | |
$res .= implode('/', $path); | |
} | |
if (!empty($url['query'])) { | |
$res .= '?' . $url['query']; | |
} | |
if (!empty($url['fragment'])) { | |
$res .= '#' . $url['fragment']; | |
} | |
return $res; | |
} else { | |
return translit_path($url); | |
} | |
} | |
echo traslit_url('https://example.com/category/статья о транслите.html?page=1'); | |
// Результат | |
// https://example.com/category/statya-o-translite.html?page=1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment