JavaScript PHP PHP Code Style & Scripts

How to generate clean url with PHP or Javascript

Hi friends, this is very basic post but useful for many websites. Following scripts will convert text into clean url using php script and another script using javascript. This script will remove unnecessary texts from the string and generate the url.

How to generate clean url with php or javascript by Anil Labs
How to generate clean url with php or javascript by Anil Labs

Script 1 : Clean URL using PHP code

<?php
        function generateCleanUrl($text)
        {
          // replace non letter or digits by -
          $text = preg_replace('~[^\\pL\d]+~u', '-', $text);

          // trim
          $text = trim($text, '-');

          // transliterate
          if (function_exists('iconv'))
          {
            $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
          }

          // lowercase
          $text = strtolower($text);

          // remove unwanted characters
          $text = preg_replace('~[^-\w]+~', '', $text);

          if (empty($text))
          {
            return 'n-a';
          }

          return $text;
        }  
    ?>

By using above script we will get clean urls without special characters and spaces replaced with ‘-‘.

We have urlencode() function in php for encoding the url, but we don’t have such specific predefined function in javascript.

Script 2 : urlencode()function using javascript

following script using for encoding the text and urls.

<script>
function urlencode (str) {
    str = (str + '').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
    replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+');
}
</script>

These functions will be useful for generating dynamic urls.

1 thought on “How to generate clean url with PHP or Javascript”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.