Breaking News
Loading...
July 7, 2015

HOW TO CONVERT STRINGS INTO A URL FRIENDLY FORMAT USING PHP OR JAVASCRIPT

2:40 PM
This function converts strings into a format that can be used in URLs. For example, the string "Mike’s Karate School" would be returned as "mikes-karate-school".
PHP Function:
/**
 * Returns a string in a URL friendly format. This function is
 * recommended to be used on non-multibyte character sets. So 
 * this is not recommended for UTF-8, since certain PHP 
 * functions (like strtolower) should not be used on multibyte
 * strings.
 * @param string $str The input string.
 * @return string The URL friendly string.
 */
public static function getUrlFriendlyString($str)
{
   // convert spaces to '-', remove characters that are not alphanumeric
   // or a '-', combine multiple dashes (i.e., '---') into one dash '-'.
   $str = ereg_replace("[-]+", "-", ereg_replace("[^a-z0-9-]", "",
      strtolower( str_replace(" ", "-", $str) ) ) );
   return $str;
}
JavaScript Function:
/**
 * Returns a string in a URL friendly format.
 * @param string str The input string.
 * @return string The URL friendly string.
 */
function getUrlFriendlyString(str)
{
   // convert spaces to '-'
   str = str.replace(/ /g, "-");
   // Make lowercase
   str = str.toLowerCase();
   // Remove characters that are not alphanumeric or a '-'
   str = str.replace(/[^a-z0-9-]/g, "");
   // Combine multiple dashes (i.e., '---') into one dash '-'.
   str = str.replace(/[-]+/g, "-");
   return str;
}
Source URL: http://jesseforrest.name/convert-strings-into-url-friendly-format-php/159

0 comments:

Post a Comment

:) :)) ;(( :-) =)) ;( ;-( :d :-d @-) :p :o :>) (o) [-( :-? (p) :-s (m) 8-) :-t :-b b-( :-# =p~ $-) (b) (f) x-) (k) (h) (c) cheer
Click to see the code!
To insert emoticon you must added at least one space before the code.

 
Toggle Footer