How to make cute url with dash

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

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 !@#$%^&*()’":;[]{})

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;

}

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.

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);

I’m using this: https://github.com/jbroadway/urlify