简体   繁体   中英

Generate slug with german umlauts

I try to generate a slug from a string, but I got some problems with the german umlauts:

$text = 'Ein schöner Text';
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
$text = trim($text, '-');
$text = iconv('utf-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
$text = preg_replace('~[^-\w]+~', '', $text);

The result should be: 'ein-schoener-text'

Change the second preg_replace line to the below because to match any letter in any language you need to use \\p{L} pattern.

$text = preg_replace('~[^\p{L}\d]+~u', '-', $text);

Code:

<?php
$text = 'Ein schöner Text';
$text = preg_replace('~[^\p{L}\d]+~u', '-', $text);
$text = trim($text, '-');
$text = iconv('utf-8', 'ASCII//TRANSLIT', $text);
$text = strtolower($text);
$text = preg_replace('~[^-\w]+~', '', $text);
echo $text;
?>

Output:

ein-schoner-text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM