必须有一个更好的正则表达式

I'm writing a small CMS and I'm trying to turn a title into a URL slug with dashes. I know I need to do a couple of things and I've got the whole thing work, but I just don't like it. The problem seems to be that if there are any special characters at the end, I'd need to remove them before it goes into the database. The only way I could figure out doing this was to do 2 preg_replace's in one statement. So it looks something like this:

preg_replace("/\-$/","",preg_replace('/[^a-z0-9]+/i', "-", strtolower($title)));

and it and turn this: (this is a title!!!)))**that is (strange))

into this: this-is-a-title-that-is-strange

But this expression just looks like ass. There has to be a better way of coding this, or something out there, I just don't know it. Any help would be greatly appreciated

You can make just one call to preg-replace with array inputs as:

preg_replace( array('/[^a-z0-9]+/','/^-|-$/'), // from array
              array('-',''),                   // to array
              strtolower($title));             

Note that your existing code retains leading - if any. The code above gets rid of that.

One option, which still requires two replacements but takes care of both the start and end dashes in one pass, is:

preg_replace('/[^a-z0-9]/', '',
  preg_replace('/([a-z0-9])[^a-z0-9]+([a-z0-9])/', '$1-$2',
    strtolower($title)));

There is also the alternative of:

implode('-',
  preg_split('/[^a-z0-9]/',
             strtolower($title),
             PREG_SPLIT_NO_EMPTY));

Use trim.

trim(preg_replace('/[^a-z0-9]+/i', "-", strtolower($title)), '-')