Skip to content

Instantly share code, notes, and snippets.

@florentb
Last active May 3, 2016 13:36
Show Gist options
  • Save florentb/bde79cb50a78773a3dde009fe22ef9a8 to your computer and use it in GitHub Desktop.
Save florentb/bde79cb50a78773a3dde009fe22ef9a8 to your computer and use it in GitHub Desktop.
PHP example to create an URL from an accented string
<?php
/**
* Replace accents
*
* Replace accented characters
* by the corresponding unaccented characters
*
* @param string $str the string
* @return string
*/
function replace_accents($str) {
$str = htmlentities($str);
$str = preg_replace('/&([a-zA-Z])(uml|acute|grave|circ|tilde);/', '$1', $str);
return html_entity_decode($str);
}
/**
* Create URL Title
*
* Takes a "title" string as input and creates a
* human-friendly URL string with either a dash
* or an underscore as the word separator.
*
* @param string $str the string
* @param string $separator the separator: dash, or underscore
* @return string
*/
function url_title($str, $separator = 'dash', $lowercase = FALSE) {
$replace = ($separator == 'dash') ? '-' : '_';
$trans = array(
'&\#\d+?;' => '',
'&\S+?;' => '',
'\s+' => $replace,
'[^a-z0-9\-\._]' => '',
$replace.'+' => $replace,
$replace.'$' => $replace,
'^'.$replace => $replace,
'\.+$' => ''
);
$str = strip_tags($str);
$str = replace_accents($str);
foreach ($trans as $key => $val) {
$str = preg_replace("#".$key."#i", $val, $str);
}
if ($lowercase === TRUE) {
$str = strtolower($str);
}
return trim(stripslashes($str));
}
/**
* ######################################
* # Example
* ######################################
*/
echo url_title("Quelques vérités bonnes à rappeler s'agissant la durée du bail commercial et sa résiliation", 'dash', true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment