Hide your secret files INSIDE photos, videos or other files with OmniHide PRO.

PHP Function to make safe URL slugs

Topics
Tags

Slugs are parts of URL which consists of human readable words. If you’re using slugs for your custom webapp, chances are that you’ll need a function to sanitize and remove special characters and URL invalid characters. Here’s a generic PHP function that would generate a slug from a string:

function make_slug($f) {
	$f = strtolower(trim(de_accent($f)));
	/* SRC: http://www.house6.com/blog/?p=83
	 * convert & to "and", @ to "at", and # to "number"	*/
	$f = preg_replace(array('/[\&]/', '/[\@]/', '/[\#]/'), array('-and-', '-at-', '-num-'), $f);
	$f = preg_replace('/[^(\x20-\x7F)]*/','', $f); /* Removes any special chars we missed above */
	$f = str_replace(' ', '-', $f);
	$f = str_replace('.', '', $f);
	$f = str_replace('\'', '', $f);
	$f = preg_replace('/[^\w\-\.]+/', '', $f);  /*Remove non-word chars (leaving hyphens and periods)*/
	$f = preg_replace('/[\-]+/', '-', $f); /* Converts groups of hyphens into one */
	return strtolower($f);
}

Usage:

$string = "PHP Function() to make safe URL Slugs ^*(!*#";
$slug  = make_slug($string);
echo $slug;  // OUTPUT: php-function-to-make-safe-url-slugs

You can use it in your projects by including the function in the include file. For wordpress themes, just add it in functions.php. For a framework like CodeIgniter or CakePHP, add the function to a helper file and use it.

 
Discover upcoming movies
 

One response to “PHP Function to make safe URL slugs”

  1. tilak says:

    thytrje

 
 

Categories