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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<?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.

1
2
3
4
5
6
7
<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 Comment

Shahnawaz · December 27, 2012 at 9:10 am

Hi,

Thanks for sharing. Did you try this code with arabic title/url.

Leave a Reply

Avatar placeholder

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