Hello everyone, Today I want to share with you one function can be generate slug of title from any language php, like this result
There is main function
If you want to like above result check and use below function. I am writing on CAKEPHP framework. so you will see CakeException, you can change it for throw or any exit from php command.
public static function transliterate( $string, $transliterator = null)
{
$_defaultTransliteratorId = ‘Any-Latin; Latin-ASCII; [u0080-u7fff] remove’;
if (empty($transliterator)) {
$transliterator = $_defaultTransliteratorId;
}
$return = transliterator_transliterate($transliterator, $string);
if ($return === false) {
throw new CakeException(sprintf(‘Unable to transliterate string: %s’, $string));
}
return $return;
}
public function gen_slug( $string, $options = [])
{
if (is_string($options)) {
$options = [‘replacement’ => $options];
}
$options += [
‘replacement’ => ‘-‘,
‘transliteratorId’ => null,
‘preserve’ => null,
];
if ($options[‘transliteratorId’] !== false) {
$string = $this->transliterate($string, $options[‘transliteratorId’]);
}
$regex = ‘^p{Ll}p{Lm}p{Lo}p{Lt}p{Lu}p{Nd}’;
if ($options[‘preserve’]) {
$regex .= preg_quote($options[‘preserve’], ‘/’);
}
$quotedReplacement = preg_quote((string)$options[‘replacement’], ‘/’);
$map = [
‘/[‘ . $regex . ‘]/mu’ => $options[‘replacement’],
sprintf(‘/^[%s]+|[%s]+$/’, $quotedReplacement, $quotedReplacement) => ”,
];
if (is_string($options[‘replacement’]) && strlen($options[‘replacement’]) > 0) {
$map[sprintf(‘/[%s]+/mu’, $quotedReplacement)] = $options[‘replacement’];
}
$string = preg_replace(array_keys($map), $map, $string);
return $string;
}
how to use it
$slug = “how are you friend?”;
pr ($this->slug($slug));
$slug = “bạn khoẻ không”;
pr ($this->slug($slug));
$slug = “祝你成功”;
pr ($this->slug($slug));
Any feedback, please leave your comment, we can discuss about it!!
Thanks for watching my blogs
Zidane