Categories
Posts

PHP Helpers: make_slug

New function, make_slug –

[sourcecode lang=”php”]
if ( !function_exists( ‘make_slug’ ) ) {
function make_slug( $str ) {
$url_str = strtolower( trim( $str ) );

$url_str = preg_replace( ‘/[s_]+/’, ‘-‘, $url_str );
$url_str = preg_replace( ‘/-{2,}/’, ‘-‘, $url_str );
$url_str = preg_replace( ‘/[^a-z0-9-]/’, ”, $url_str );

return $url_str;
}
}
[/sourcecode]

This takes a string and returns a slug that is more URL friendly. For example “Do This_Today – Please” would become “do-this-today-please“.

The approach is pretty simple:

  • lower case everything (line 3)
  • replace space and underscore with dash (line 5)
  • replace two or more dashes with a single dash (line 6)
  • remove any other characters that aren’t a-z, 0-9 or a dash (line 7)

2 replies on “PHP Helpers: make_slug”

Leave a Reply

Your email address will not be published. Required fields are marked *