Setting a permanent link with PHP

I've found the following function in Practical Web 2.0 applications with PHP and MySQL:


function generateUniqueUrl($title)
{
  $url = strtolower($title);

  $filters = array (
                    '/&+/' => 'and',
                   '/[^a-z0-9]+/i' => '-',
                   '/-+/' => '-' );

  foreach($filters as $re => $replacement) {
    $url = preg_replace($re, $replacement, $url);
  }

  $url = trim($url, '-');
  $url = trim(substr($url, 0, 30));

  if(strlen($url) == 0) {
    $url = 'post';
  }

  // find similar URLs in the database
  
  $query = sprintf("select url from %s where id_user = %d and url like ?", $this->_table, $this->id_user);
  $query = $this->_db->quoteInto($query, $url . '%');
  $result = $this->_db->fetchCol($query);

  if(count($result) == 0 || !in_array($url, $result)) {
    return $url;
  }

  // generate an unique URL

  $i = 2;

  do {
    $_url = $url . '-' . $i++;
  } while(in_array($_url, $result));

  return $_url;
}

This function first filters all special characters that may occur in a post title, then check if there are similar URLs in other posts and finally generates an unique post identifier using a counter attached to the main URL. Very interesting!

Leave a Reply

Note: Only a member of this blog may post a comment.