Skip to content

Instantly share code, notes, and snippets.

@jaydeepakbari
Last active November 14, 2018 09:34
Show Gist options
  • Save jaydeepakbari/a5eee4b83c87ce740d4790a159fb31e4 to your computer and use it in GitHub Desktop.
Save jaydeepakbari/a5eee4b83c87ce740d4790a159fb31e4 to your computer and use it in GitHub Desktop.
Generate SEO friendly URLs (slugs) Using PHP
<?php
function format_uri( $string, $separator = '-' )
{
$accents_regex = '~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i';
$special_cases = array( '&' => 'and', "'" => '');
$string = mb_strtolower( trim( $string ), 'UTF-8' );
$string = str_replace( array_keys($special_cases), array_values( $special_cases), $string );
$string = preg_replace( $accents_regex, '$1', htmlentities( $string, ENT_QUOTES, 'UTF-8' ) );
$string = preg_replace("/[^a-z0-9]/u", "$separator", $string);
$string = preg_replace("/[$separator]+/u", "$separator", $string);
return $string;
}
echo format_uri("#@&~^!âèêëçî");
//outputs : -and-aeeeci
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment