Created
April 29, 2011 15:53
-
-
Save ruflin/948510 to your computer and use it in GitHub Desktop.
Convert string to url string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Transforms a string to a valid url parameter | |
* | |
* @param string $string String to transform to valid url | |
* @param int $limit Max length of return string. Default is 255, because url shouldn't be longer | |
* @return string | |
*/ | |
public static function toUrl($string, $limit = 255) { | |
$string = self::toAscii($string, true); | |
$string = str_replace('.', '-', $string); | |
$string = substr($string, 0, $limit); | |
return $string; | |
} | |
/** | |
* Transform a string to ascii signs (and "-") | |
* Usable if a string should be shown in url | |
* | |
* @param string $string String to transform | |
* @param boolean $lowerCase OPTIONAL True if output string should be lower case | |
* @return string Ascii String | |
*/ | |
public static function toAscii($string, $lowerCase = true) { | |
// removes white spaces | |
$string = trim($string); | |
// Split up all special signs like ä in two characters | |
$string = iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $string); | |
// Replace white spaces by dashes | |
$string = str_replace(' ', '-', $string); | |
// Make string lower case | |
if ($lowerCase) { | |
$string = mb_strtolower($string); | |
} | |
// Remove all signs that are not \w or dashes or dots | |
$string = preg_replace('/([^\w-\.])/', '', $string); | |
return $string; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment