Skip to content

Instantly share code, notes, and snippets.

@codeasashu
Created June 4, 2018 13:35
Show Gist options
  • Select an option

  • Save codeasashu/5414b139ab1ccddc47d2f8177f810d96 to your computer and use it in GitHub Desktop.

Select an option

Save codeasashu/5414b139ab1ccddc47d2f8177f810d96 to your computer and use it in GitHub Desktop.
Generate Slugs based on titles
function createSlug($title = null, $id = 0)
{
$maxTries = 10; // Max recursion limit
if(!$title) {
throw new \Exception('Please mention title to generate the slug');
}
// Normalize the title
$slug = str_slug($title);
// Get any that could possibly be related.
// This cuts the queries down by doing it once.
$allSlugs = getRelatedSlugs($slug, $id);
// If we haven't used it before then we are all good.
if (!isset($allSlugs['slug'])){
return $slug;
}
$count = 1;
while(true){
$newSlug = $slug.'-'.$count;
if ($allSlugs['slug'] != $newSlug){
return $newSlug;
}
if($count === $maxTries) break;
$count++;
}
throw new \Exception('Can not create slug. Limit exhausted');
}
function getRelatedSlugs($slug, $id = 0)
{
$slugCol = ''; // DB slug column
$slugTbl = ''; // DB table containing slug
if(!isset($slugCol)){
throw new \Exception('Please mention slug column in model');
}
$sql = 'select * from '. $slugTbl . ' where '. $slugCol . ' LIKE "'. $slug . '%" LIMIT 1';
// Execute SQL and return row if found.
return exec_sql($sql);
}
function str_slug($string)
{
$slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
return $slug;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment