SEO friendly URL in PHP

When I started implementing mod_rewrite in websites I had a problem in PHP as how to make a SEO friendly URL. All tutorials were geared towards how to implement mod_rewrite, about modifying .htaccess files, but none treated how to make the urls friendly with dynamic content. For example I have a news section which are pulled from the database, but how can I make the URL friendly with the title.

For example, my problem was to convert titles like “Barca rejects FIFA statement on Olympics row” into “barca-rejects-fifa-statement-on-olympics-row.html”. The trick has to work also with french titles (I’am sure my friends at Nexen will appreciate ;-)) like “Guantanamo: le chauffeur de Ben Laden plaide non coupable à l’ouverture de son procès” into “guantanamo-le-chauffeur-de-ben-laden-plaide-non-coupable-a-l-ouverture-de-son-proces.html”, removing all french accentuated characters.

Hopefully I came across this function which I think might help you too :

function friendlyURL($string){
	$string = preg_replace("`\[.*\]`U","",$string);
	$string = preg_replace('`&(amp;)?#?[a-z0-9]+;`i','-',$string);
	$string = htmlentities($string, ENT_COMPAT, 'utf-8');
	$string = preg_replace( "`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i","\\1", $string );
	$string = preg_replace( array("`[^a-z0-9]`i","`[-]+`") , "-", $string);
	return strtolower(trim($string, '-'));
}

Use :

$myFriendlyURL = friendlyURL("Barca rejects FIFA statement on Olympics row");
echo $myFriendlyURL; // will echo barca-rejects-fifa-statement-on-olympics-row

You just have to concatenate anything you want with the string afterwards. For french users, make sure your string is encoded in UTF-8 else it won’t work.

If you’re using the Smarty templating engine I made a little modifier which you can download. Extract the zip file in your Smarty/libs/plugins/ folder and to use it in your templates :

{"Barca rejects FIFA statement on Olympics row" | friendlyURL}

Or if your string is in a variable :

{$yourString | friendlyURL}
Be Sociable, Share!

Comments (28)

  1. 12:22 pm, July 25, 2008Dumitru  / Reply

    this is my function for friendly Romanian URLS:

    public function setId( $id, $nume )
    {
    $nume = strToLower( $nume );
    $nume = str_replace( array( ” “, “ş”, “Ş”, “Ţ”, “ţ”, “ă”, “î”, “â” ),
    array( “-”, “s”, “s”, “t”, “t”, “a”, “i”, “a” ),
    $nume );
    $nume = preg_replace( “/[^a-zA-Z0-9\-]/”, “-”, $nume );
    $nume = urlEncode( $nume );
    $url = $id . “-” . $nume . ‘.html’;
    return $url;
    }

  2. 12:36 pm, July 25, 2008asvin  / Reply

    thanks for the tip Dumitru ;-)

  3. 3:51 am, July 29, 2008materix  / Reply

    Thx for the function.

    What is your experience the easiest way to implement reading of seo friendly urls? (e.g. mod_rewrite)

  4. 9:44 am, July 29, 2008asvin  / Reply

    The easiest way to implement it is to use htaccess files. Create one and simply put these :

    RewriteEngine on
    RewriteRule ^my-friendly-url.html$ myphppage.php?id=2

  5. 4:24 pm, July 29, 2008materix  / Reply

    Do you know if it possible to build the .htaccess file automatically?
    It is a bit tedious to update the file with a new RewriteRule, every time a new page is added.

  6. 6:36 pm, July 29, 2008asvin  / Reply

    materix,

    Maybe you’re talking about RewriteMap.
    Check out this link :
    http://www.onlamp.com/pub/a/apache/2005/04/28/apacheckbk.html

  7. 8:45 pm, October 10, 2008Nitish  / Reply

    Well I have been using symfony for a while, I have seen the routing engine built is very for building SEO friendly url without knowledge of mod_rewrite or any other technique…

  8. 7:16 pm, October 17, 2008Mark S.  / Reply

    To say the least, mods in the .htaccess for rewriting purposes are ineffective with a site that has products, categories, articles etc.

    If you need 100% static URLs you need to utilize database tables of such entities. Checkout how the SEO-G module performs that. (You could check my site where it is deployed)

    As of the different languages yes you do need a simple filtering method to modify the characters. But if you have such an SEO module in place, this can be done when a new product, article etc is created or edit the url afterwards.

  9. 5:38 am, April 2, 2009thewackonerd  / Reply

    Hi, this is just what I am after, the only trouble is I don’t have a clue as to ho to use it.Can you show it in relation to the header and body tags? and a link as well … thanks

  10. 9:37 am, April 2, 2009asvin  / Reply

    @thewackonerd

    You can use the function like this :
    $myFriendlyURL = friendlyURL(“Barca rejects FIFA statement on Olympics row”);
    echo $myFriendlyURL; // will echo barca-rejects-fifa-statement-on-olympics-row

    In fact you must write your rewriting rules separately.

    Let me know if it’s OK,

  11. 3:45 am, April 3, 2009thewackonerd  / Reply

    Hi Asvin, as usual I typed before engaging brain, I have it all working and it is exactly what I wanted / needed for my sites, thanks again for the code.

  12. 11:38 am, April 3, 2009asvin  / Reply

    NP thewack ;-)

  13. 10:22 pm, July 30, 2009Tom Cox  / Reply

    Thanks for this plugin!

    Very useful as I use .htaccess to modify urls, although I needed a a specific PHP script to rewrite the title of urls added by my CMS.

    This does the job perfectly.

    Thanks again!!

  14. 9:16 am, August 5, 2009David  / Reply

    How do u use “barca-rejects-fifa-statement-on-olympics-row.html” to find the corresponding post in my database ?

    - Perhaps convert “barca-rejects-fifa-statement-on-olympics-row.html” back to Barca rejects FIFA statement on Olympics row” and search for this title in my database ?!?

  15. 5:20 am, August 28, 2009Atolos  / Reply

    Thank you very much !!! i changed a little bit for my need with some foraign characters
    but your idea was perfect for me !!!

    $string = preg_replace(“`\[.*\]`U”,”",$string);
    $string = preg_replace(array(“`Ç`i”,”`ç`i”,”`Ö`i”,”`ö`i”,”`Ä`i”,”`ä`i”,”`Ü`i”,”`ü`i”,”`Ç`i”,”`ç`i”,”`İ`i”,”`ı`i”,”`Ş`i”,”`ş`i”,”`Ğ`i”,”`ğ`i”),array(“c”,”c”,”o”,”o”,”a”,”a”,”u”,”u”,”c”,”c”,”i”,”i”,”s”,”s”,”g”,”g”),$string);
    $string = preg_replace(‘`&(amp;)?#?[a-z0-9]+;`i’,'_’,$string);
    $string = htmlentities($string, ENT_COMPAT, ‘utf-8′);
    $string = preg_replace( “`&([a-z])(acute|uml|circ|grave|ring|cedil|slash|tilde|caron|lig|quot|rsquo);`i”,”\\1″, $string );
    $string = preg_replace( array(“`[^a-z0-9]`i”,”`[-]+`”) , “_”, $string);
    return strtolower(trim($string, ‘_’));

  16. 10:31 pm, August 30, 2009Rob  / Reply

    Hi,

    Nice article. I shamelessly used your neat little function in my seo url article – http://www.web-design-talk.co.uk/116/seo-friendly-urls-with-mod-rewrite/ :)

    Thanks

  17. 6:51 pm, September 21, 2009Hitesh  / Reply

    Can you tell what I need to do to make seo friendly urls for my site http://www.ipl-schedule.com . I created site by paying 300$ but I have no idea about php.

  18. 6:52 pm, October 9, 2009Samuel Koh  / Reply

    Asvin,

    Many thanks for this code! Works wonderfully… just what I’m looking for!

  19. 2:31 am, October 30, 2009ron  / Reply

    Hi Asvin,

    Is this used for displaying only ?

    I have tried it but how do I convert it back to it’s orignal format so that I can click on the link ?

    Thanks,

    Ron

  20. 5:02 pm, December 23, 2009Hernan Benson  / Reply

    Hey, thanks for this function, i have used it and its really nice.

    Happy New Year for all!

    -HR-

  21. 9:30 pm, January 13, 2010jimmy  / Reply

    @Hitesh

    go to http://www.freelancereference.com and hire a programmer (at affortable rates) to do it for you because its not that easy

  22. 2:08 pm, February 7, 2010omerts  / Reply

    how can I reverse this function?

  23. 7:59 am, February 17, 2010Anil Kumar Panigrahi  / Reply

    Thank you for giving valuable information, but i need seo urls like facebook, i mean urls with dots.

    http://www.facebook.com/anil.kumar.panigrahi

    like that, can you suggest me.

    thank you.

  24. 3:24 am, March 10, 2010simon  / Reply

    can you ether email me or supply a url where I can find the smarty plug-in that you ref to in your post.

  25. 9:21 am, March 17, 2010dental internet marketing  / Reply

    thanks for the fix!

  26. 3:36 pm, May 22, 2010SRGIT  / Reply

    Good article, it’s help me. Let me know Is it working same as Yahoo and MSN search engine?

  27. 9:34 am, August 16, 2010cihip  / Reply

    SEO friendly URL in PHP post for thanx.

  28. 1:59 am, October 27, 2010Cincinnati Web Design  / Reply

    this is one of those “must know” tutorials. seo becomes more important to clients every day. you must let search engines know what data is on your site. great info. thanks

Leave a Reply

Allowed Tags - You may use these HTML tags and attributes in your comment.

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>