xent
(Bro Xentauri)
February 8, 2011, 12:43am
1
hi all i want to ask how to convert blank space or plus sign (when using chtml::encode) into dash in URL.
I have made function in every model to convert blank space into dash, and its work fine (it is harder if implemented every model ).
Does Yii have built-in function to do that?
thanks for advice
zaccaria
(Matteo Falsitta)
February 8, 2011, 9:00am
2
As far as I know, there is no such a function.
If you use the url system yii will convert in the urlencoded value, so blank space will not be a problem.
Usually I adopt this rule:
preg_replace('/[^a-z0-9_]/','',strtolower( str_replace(" ", "_", $text)))
All spaces to dash, then lower case and then I delete whatever is not a letter, a number or a dash. (for avoid any possible !@#$%^&*()’":;[]{})
dimis283
(Dimis283)
February 8, 2011, 9:56am
3
I found this code that filters a string into a “friendly” string for use in URL’s. It converts the string to lower case and replaces any non-alphanumeric (and accented) characters with dashes.
function slug($str)
{
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
return $str;
}
zaccaria
(Matteo Falsitta)
February 8, 2011, 10:14am
4
Nice function, better than mine, it changes antyhing to dash instead of delete as I did.
I think I will adopt it, thank for sharing.
choicehunt
(Choicehunt)
December 24, 2013, 12:21pm
5
dimis283:
I found this code that filters a string into a “friendly” string for use in URL’s. It converts the string to lower case and replaces any non-alphanumeric (and accented) characters with dashes.
function slug($str)
{
$str = strtolower(trim($str));
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
return $str;
}
where we use in our project, how to add this function, someone help on it…
just one small enhancement.
This
$str = preg_replace('/[^a-z0-9-]/', '-', $str);
$str = preg_replace('/-+/', "-", $str);
can be changed to this
$str = preg_replace('/[^a-z0-9-]+/', '-', $str);
or even this
$str = preg_replace('/[\W_]+/', '-', $str);
twisted1919
(Serban Cristian)
December 24, 2013, 12:52pm
7