I'm developing a small CMS system. Currently brain dead while trying to generate a unique url. I generate the url from the title of the page. Got a nice script to make this happen but I can't resolve the issue of duplicates.
Similar question here but getting the exact output.
I manage to make the following;
this-is-the-slug
this-is-the-slug-2
But if I create the same post the third time, it would just duplicate: this-is-the-slug-2
$i = 1;
$baseurl = $url;
//$check database here
if($thereisamatch){
$url = $baseurl . "-" . $i++;
}
I can't get around it, would be thankful for assistance.
if(isset($_POST['save'])) {
$title = mysqli_real_escape_string($db, $_POST['title']);
$url = toAscii($title);
// check url
$content = $_POST['content'];
$author = $_SESSION['thelab_username'];
$type = $_POST['type'];
$showtitle = $_POST['showtitle'];
$saveas = $_POST['status'];
$insert = $connection->query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");
if($insert === TRUE) {
echo '<div id="success">Page added. <button id="close">Close</button></div>';
}
else {
echo '<div id="error">Failed. Try again. <button id="failed">Close</button></div>';
printf("Errormessage: %s
", $db->error);
}
}
function toAscii($str, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
return $clean;
}