title: Generate unique url slug with PHP
body: <p>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.</p>
  
  <p>Similar question <a href="https://stackoverflow.com/questions/20439834/make-a-post-slug-unique">here</a> but getting the exact output.</p>
  
  <p>I manage to make the following;</p>
  
  <pre><code>this-is-the-slug
  this-is-the-slug-2
  </code></pre>
  
  <p>But if I create the same post the third time, it would just duplicate: <code>this-is-the-slug-2</code></p>
  
  <pre><code>$i = 1;
  $baseurl = $url;
  //$check database here
  if($thereisamatch){
  $url = $baseurl . "-" . $i++;  
  }
  </code></pre>
  
  <p>I can't get around it, would be thankful for assistance.</p>
  
  <pre><code>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-&gt;query(" INSERT INTO lab_pages (title, permalink, content, author, status, type, showtitle)
      VALUES ('$title', '$newslug', '$content', '$author', '$saveas', '$type', '$showtitle') ");
  
      if($insert === TRUE) {
          echo '&lt;div id="success"&gt;Page added. &lt;button id="close"&gt;Close&lt;/button&gt;&lt;/div&gt;';
      }
  
      else {
          echo '&lt;div id="error"&gt;Failed. Try again. &lt;button id="failed"&gt;Close&lt;/button&gt;&lt;/div&gt;';
          printf("Errormessage: %s\n", $db-&gt;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;
  }
  </code></pre>