SEO friendly URL in PHP

SEO friendly

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}
 
Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • StumbleUpon
  • Mixx
  • Ma.gnolia
  • Technorati
  • Netvouz
  • Reddit
  • Propeller
  • Slashdot
  • DZone

21 Comments to “SEO friendly URL in PHP”

  1. Dumitru 25 July 2008 at 12:22 pm #

    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. asvin 25 July 2008 at 12:36 pm #

    thanks for the tip Dumitru ;-)

  3. materix 29 July 2008 at 3:51 am #

    Thx for the function.

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

  4. asvin 29 July 2008 at 9:44 am #

    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. materix 29 July 2008 at 4:24 pm #

    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. asvin 29 July 2008 at 6:36 pm #

    materix,

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

  7. Nitish 10 October 2008 at 8:45 pm #

    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. Mark S. 17 October 2008 at 7:16 pm #

    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. [...] If you are interested on how to do it, check apache mod-rewrite or you can read more about how to do “Friendly URLS with PHP” at “The html blog“ [...]

  10. thewackonerd 2 April 2009 at 5:38 am #

    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

  11. asvin 2 April 2009 at 9:37 am #

    @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,

  12. thewackonerd 3 April 2009 at 3:45 am #

    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.

  13. asvin 3 April 2009 at 11:38 am #

    NP thewack ;-)

  14. [...] string based on your topic, or in my case, the name of the individual, you need to create a string substitution function, like [...]

  15. Tom Cox 30 July 2009 at 10:22 pm #

    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!!

  16. David 5 August 2009 at 9:16 am #

    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 ?!?

  17. [...] http://htmlblog.net/seo-friendly-url-in-php/ [...]

  18. [...] the title through a function. As the one I use is a at work I shamelessly used the one from the html blog. Here’s the PHP to generate our links page (note, I used a simple loop to output the links for [...]

  19. Atolos 28 August 2009 at 5:20 am #

    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, ‘_’));

  20. Rob 30 August 2009 at 10:31 pm #

    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

  21. Hitesh 21 September 2009 at 6:51 pm #

    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.


Leave a Reply