Search code examples
phpparametersurlencodesymbolsslug

Looking to finish my url encoding in php


I have a slug function that I am using from another tutorial.

 public function createSlug($slug) {
        // Remove anything but letters, numbers, spaces, hypens
        // Remove spaces and duplicate dypens
        // Trim the left and right, removing any left over hypens
        
        $lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
        $spacesDuplicateHypens = '/[\-\s]+/';

        $slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));   
        $slug = preg_replace($spacesDuplicateHypens, '-', $slug);
        $slug = trim($slug, '-');
        
        return $slug;
    }

It works great. I have two questions.

  1. It gives me 'amp' instead of removing the '&' symbol. Not sure if it should be like that.

    For eg.

original url

http://www.mywebsite.com?category_id=1&category_name=hot & dogs 

new url using slug function

http://www.mywebsite.com?category_id=1&category_name=hot-amp-dogs

and second, how do I decode it back to the original form so that I can echo it out on the page? It doesn't look right echoing with dashes.


Solution

  • Use "htmlspecialchars_decode". see below modified function:

    function createSlug($slug) {
    // Remove anything but letters, numbers, spaces, hypens
    // Remove spaces and duplicate dypens
    // Trim the left and right, removing any left over hypens
    $slug   =   htmlspecialchars_decode($slug);
    
    $lettersNumbersSpacesHypens = '/[^\-\s\pN\pL]+/u';
    $spacesDuplicateHypens = '/[\-\s]+/';
    
    $slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug, 'UTF-8'));   
    $slug = preg_replace($spacesDuplicateHypens, '-', $slug);
    $slug = trim($slug, '-');
    
    return $slug;
    }
    

    For decode, agree with Rakesh Sharma. Use database to manage this.