PHP Create a slug from a string

This is the ultimate slug generator. It allows restriction to a maximum length, removes html tags & entities and converts accented characters.
public function createSlug($string, $separator = '-', $maxlength = 96) {
	$accents_regex = '~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i';
	$string = preg_replace( $accents_regex, '$1', $string); // replace accented characters

	$string = preg_replace('/&(?:[a-z\d]+|#\d+|#x[a-f\d]+);/i', '', $string); // strip html entities (must be done before 'reserved' characters are replaced)

	$string = mb_strtolower( trim( $string ), 'UTF-8' ); // to lower

	$special_cases = array( '&' => 'and', "'" => '');
	$string = str_replace( array_keys($special_cases), array_values( $special_cases), $string ); // replace 'reserved' characters

	$string = preg_replace('/<[^>]*>/', '', $string); // strip html tags
	$string = preg_replace("/[^a-z0-9]/u", "$separator", $string); // create safe url
	$string = preg_replace("/[$separator]+/u", "$separator", $string); // replace spaces


	if (strlen($string) > $maxlength && strpos($string, $separator) !== false) {

		$string = mb_substr($string, 0, strrpos($string, $separator)); // reduce to max length
	
		if (strlen($string) > $maxlength) {
			if (strpos($string, $separator) !== false) {
				// if it's still too long, remove one more 'section'
				$sections = explode($separator, $string);
				array_pop($sections);
				$string = implode($separator, $sections);
			}
			else {
				// if there is only one section, we need to crop the string - sad :(
				$string = mb_substr($string, 0, $maxlength);							
			}
		}
	}
	else {
		// if there is only one section, we need to crop the string - sad :(
		$string = mb_substr($string, 0, $maxlength);							
	}

	$string = rtrim($string, '-');

	return $string;
}	
Posted by
Snippet Viewed 1739 times.

Share your PHP code snippets:

  • Get some recognition & a link back to your site.
  • Create your own code library.
  • Help your fellow developers, as they have helped you.

 

Submit | Browse

Most Recent php snippets

Most Viewed