convert to sef url function

Coding Critique is the place to post source code for peer review by other members of DevNetwork. Any kind of code can be posted. Code posted does not have to be limited to PHP. All members are invited to contribute constructive criticism with the goal of improving the code. Posted code should include some background information about it and what areas you specifically would like help with.

Popular code excerpts may be moved to "Code Snippets" by the moderators.

Moderator: General Moderators

Post Reply
php4newbies
Forum Newbie
Posts: 3
Joined: Thu Jan 01, 2009 4:38 pm

convert to sef url function

Post by php4newbies »

I have framework I created and I've created a few 'helper' functions. One function is converting a user entered title (actually a blog post title) I am storing the title and also storing a 'seo_title' the blog post is pulled based on the url entered.
So, when some goes to mysite com/this-is-a-sef-url it uses 'this-is-a-sef-url' to get that blog post.
Anyway here is the function I use to convert:

Code: Select all

function convert_to_sef_url($str)
{
    $str = str_replace("'","",$str); //replace ' with nothing
    $str = str_replace('"',"",$str); //replace " with nothing
    $str = preg_replace("/[^a-zA-Z0-9_-]/","-", $str); //convert non alphanumeric and non - _ to -
    $str = preg_replace ( "/-+/" , "-" , $str ); //convert multiple dashes to a single dash
    $str = strtolower($str);
    return $str;
}
It works great. can anyone think of a more efficient way or find any bugs?
I want to make sure only a-z and A-Z and 0-9 and underscores and dashes are the only things allowed in the sef url and no multiple dashes. I think I've got everything but a fresh pair of eyes is always nice.
User avatar
Syntac
Forum Contributor
Posts: 327
Joined: Sun Sep 14, 2008 7:59 pm

Re: convert to sef url function

Post by Syntac »

Well, since you replace all invalid characters not in the whitelist with "-", I'd say you've got everything.

Although SEF is a bit of a misnomer here. All proper search engines can handle query strings. Do you mean UEF (User Eye Friendly), maybe? :)
php4newbies
Forum Newbie
Posts: 3
Joined: Thu Jan 01, 2009 4:38 pm

Re: convert to sef url function

Post by php4newbies »

Syntac wrote:Well, since you replace all invalid characters not in the whitelist with "-", I'd say you've got everything.

Although SEF is a bit of a misnomer here. All proper search engines can handle query strings. Do you mean UEF (User Eye Friendly), maybe? :)
Yes your probably right I never was good with naming conventions - I once got reprimanded at work for having a table named promo_or_setup_user_code_usage_assoc_table was told to use discount_use_table instead :)
Post Reply