Background
Break News
How to add local font to Tailwind Css and NextJS? - Tutorial Design Pattern? - Blockchain Technology, How to create own Bitcoin virtual currency - Zustand mordern management state - Design Pattern - Flyweight Pattern? - Docker Full training Topic

[Tips] How to generate slug of title from any language PHP

Friday 26 February 2021
|
Read: Completed in minutes

[Tips] How to generate slug of title from any language PHP

A slug is a part of a URL that identifies a specific page on a website in a human-readable and SEO-friendly way. For example, the slug for this article is "how-to-generate-slug-of-title-from-any-language-php". A slug usually consists of lowercase letters, numbers, and hyphens, and it should reflect the main keywords and topic of the page.

Generating a slug from a title in PHP can be done in several steps, such as:

•  Converting the title to lowercase using the strtolower function.

•  Removing any leading or trailing spaces using the trim function.

•  Replacing any non-alphanumeric characters or spaces with hyphens using the preg_replace function and a regular expression.

•  Removing any duplicate hyphens using the preg_replace function and another regular expression.

However, this method may not work well for titles that contain characters from other languages, such as Chinese, Arabic, or Russian. These characters may not be converted correctly to lowercase, or they may be removed entirely by the regular expression. This can result in an inaccurate or empty slug that does not match the title or the content of the page.

To solve this problem, we can use a PHP extension called intl, which provides various functions for internationalization and localization. One of these functions is transliterator_transliterate, which can convert any string from one script or writing system to another. For example, we can use this function to transliterate Chinese characters to Latin characters, or Arabic characters to ASCII characters.

Using this function, we can modify our slug generation method as follows:

•  Transliterating the title to ASCII using the transliterator_transliterate function with the "Any-Latin; Latin-ASCII" option.

•  Converting the title to lowercase using the strtolower function.

•  Removing any leading or trailing spaces using the trim function.

•  Replacing any non-alphanumeric characters or spaces with hyphens using the preg_replace function and a regular expression.

•  Removing any duplicate hyphens using the preg_replace function and another regular expression.

This method should work for any title in any language, as long as the intl extension is installed and enabled on your PHP server. You can check if the extension is available using the extension_loaded function with the "intl" parameter.

Here is an example of how to use this method in CakePHP code: 

How to generate slug of title from any language PHP

 
How to generate slug of title from any language PHP

 

 

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;
    }
    

And how to use it? Here is the answer πŸ˜‹

	
      	$slug = "how are you friend?";
        pr ($this->slug($slug));
        $slug = "bαΊ‘n khoαΊ» khΓ΄ng";
        pr ($this->slug($slug));
        $slug = "η₯δ½ ζˆεŠŸ";
        pr ($this->slug($slug));
    


I hope this blog post helps you with generating slug of title from any language in CakePHP
#slug #php #url #seo #intl #transliteration #regex #lowercase #hyphen #ascii
 
Thank you for reading this post. I hope you found it helpful and easy to follow. If you have any feedback or questions about How to generate slug of title from any language PHP , please share them in the comments below. I would love to hear from you and discuss this topic further
✋✋✋✋  Webzone Tech Tips Zidane, all things tech tips web development  - I am Zidane, See you next time soon ✋✋✋✋

πŸ™‡πŸΌ Your Feedback Is Valuable and Helpful to Us - Webzone - all things Tech Tips web development Zidane πŸ™‡πŸΌ
Popular Webzone Tech Tips topic maybe you will be like it - by Webzone Tech Tips - Zidane
As a student, I found Blogspot very useful when I joined in 2014. I have been a developer for years . To give back and share what I learned, I started Webzone, a blog with tech tips. You can also search for tech tips zidane on Google and find my helpful posts. Love you all,

I am glad you visited my blog. I hope you find it useful for learning tech tips and webzone tricks. If you have any technical issues, feel free to browse my posts and see if they can help you solve them. You can also leave a comment or contact me if you need more assistance. Here is my blog address: https://learn-tech-tips.blogspot.com.

My blog where I share my passion for web development, webzone design, and tech tips. You will find tutorials on how to build websites from scratch, using hot trends frameworks like nestjs, nextjs, cakephp, devops, docker, and more. You will also learn how to fix common bugs on development, like a mini stackoverflow. Plus, you will discover how to easily learn programming languages such as PHP (CAKEPHP, LARAVEL), C#, C++, Web(HTML, CSS, javascript), and other useful things like Office (Excel, Photoshop). I hope you enjoy my blog and find it helpful for your projects. :)

Thanks and Best Regards!
Follow me on Tiktok @learntechtips and send me a direct message. I will be happy to chat with you.
Webzone - Zidane (huuvi168@gmail.com)
I'm developer, I like code, I like to learn new technology and want to be friend with people for learn each other
I'm a developer who loves coding, learning new technologies, and making friends with people who share the same passion. I have been a full stack developer since 2015, with more than years of experience in web development.
Copyright @2022(November) Version 1.0.0 - By Webzone, all things Tech Tips for Web Development Zidane
https://learn-tech-tips.blogspot.com