free hit counter

The perfect PHP clean url generator 23

THE PERFECT PHP CLEAN URL GENERATOR

In my hunt for the perfect clean url (smart url, slug, permalink, whatever) generator I’ve always slipped in some exception or bug that made the function a piece of junk. But I recently found an easy solution I hope I could call “definitive”.

Clean url generators are crucial for search engine optimization or just to tidy up the site navigation. They are even more important if you work with international characters, accented vowels /à, è, ì, .../, cedilla /ç/, dieresis /ë/, tilde /ñ/ and so on.

First of all we need to strip all special characters and punctuation away. This is easily accomplished with something like:

function toAscii($str) {
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $str);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", '-', $clean);

	return $clean;
}

With our toAscii function we can convert a string like “Hi! I’m the title of your page!” to hi-im-the-title-of-your-page. This is nice, but what happens with a title like “A piñata is a paper container filled with candy”?

The result will be a-piata-is-a-paper-container-filled-with-candy, which is not cool. We need to convert all special characters to the closest ascii character equivalent.

There are many ways to do this, maybe the easiest is by using iconv.

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str) {
	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_| -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_| -]+/", '-', $clean);

	return $clean;
}

I always work with UTF-8 but you can obviously use any character encoding recognized by your system. Thepiñata text is now transliterated into a-pinata-is-a-paper-container-filled-with-candy. Lovable.



If they are not Spanish, users will hardly search your site for the word piñata, they will most likely search forpinata. So you may want to store both versions in your database. You may have a title field with the actual displayed text and a slug field containing its ascii version counterpart.

We can add a delimiter parameter to our function so we can use it to generate both clean urls and slugs (in newspaper editing, a slug is a short name given to an article that is in production, source).

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $delimiter='-') {
	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}

// echo toAscii("A piñata is a paper container filled with candy.", ' ');
// returns: a pinata is a paper container filled with candy

There’s one more thing. The string “I’ll be back!” is converted to ill-be-back. This may or may not be an issue depending on your application. If you use the function to generate a searchable slug for example, looking for “ill” would return the famous Terminator quote that probably isn’t what you wanted.

setlocale(LC_ALL, 'en_US.UTF8');
function toAscii($str, $replace=array(), $delimiter='-') {
	if( !empty($replace) ) {
		$str = str_replace((array)$replace, ' ', $str);
	}

	$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
	$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
	$clean = strtolower(trim($clean, '-'));
	$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

	return $clean;
}

You can now pass custom delimiters to the function. Calling toAscii("I'll be back!", "'") you’ll get i-ll-be-back. Also note that the apostrophe is replaced before the string is converted to ascii as character encoding conversion may lead to weird results, for example é is converted to 'e, so the apostrophe needs to be parsed before the string is mangled by iconv.

The function seems now complete. Lets stress test it.

echo toAscii("Mess'd up --text-- just (to) stress /test/ ?our! `little` \\clean\\ url fun.ction!?-->");
returns: messd-up-text-just-to-stress-test-our-little-clean-url-function

echo toAscii("Perché l'erba è verde?", "'"); // Italian
returns: perche-l-erba-e-verde

echo toAscii("Peux-tu m'aider s'il te plaît?", "'"); // French
returns: peux-tu-m-aider-s-il-te-plait

echo toAscii("Tänk efter nu – förr'n vi föser dig bort"); // Swedish
returns: tank-efter-nu-forrn-vi-foser-dig-bort

echo toAscii("ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖÙÚÛÜÝßàáâãäåæçèéêëìíîïðñòóôõöùúûüýÿ");
returns: aaaaaaaeceeeeiiiidnooooouuuuyssaaaaaaaeceeeeiiiidnooooouuuuyy

echo toAscii("Custom`delimiter*example", array('*', '`'));
returns: custom-delimiter-example

echo toAscii("My+Last_Crazy|delimiter/example", '', ' ');
returns: my last crazy delimiter example

I’m sure we are far from perfection and probably some php/regex guru will soon bury me under my ignorance suggesting an über-simple alternative to my function. What do you thing?

Source : http://cubiq.org/the-perfect-php-clean-url-generator

23 thoughts on “The perfect PHP clean url generator

  1. Reply home remodel contractor Jun 6,2014 12:42 am

    Link exchange is nothing else however it is just placing the other person’s webpage link on your page at
    appropriate place and other person will also do same in favor of you.

  2. Reply http://k4portland.com/ Jun 6,2014 2:47 am

    Excellent way of telling, and pleasant post to take information regarding my
    presentation subject, which i am going to present in academy.

  3. Reply ASDA Jun 20,2014 12:47 pm

    You do have to have to review them up in higher
    detail in purchase to realize what positive aspects you would
    in fact take pleasure in on obtaining them. Apart from remaining
    a helpful personal savings resource for long term generations and especially people youngsters
    who may well not otherwise have had anything at all
    set apart it can be also staying plugged as a scheme aimed at economic training.
    You would commonly have to remedy consumer queries and
    information them to uncover confident items.

  4. Reply namhankang.com Jul 2,2014 5:18 pm

    That is really fascinating, You are an excessively professional blogger.

    I have joined your rss feed and sit up for looking for more of your wonderful post.
    Also, I have shared your site in my social networks

  5. Reply Shelli Jul 9,2014 9:39 pm

    After looking into a few of the blog articles on your site, I seriously appreciate your way
    of writing a blog. I book-marked it to my bookmark website
    list and will be checking back soon. Please check out my web site as
    well and tell me your opinion.

  6. Reply goji pro emagrece Jul 14,2014 2:18 pm

    hey there and thank you for your info

  7. Reply https://mlbballparkempiresupport.zendesk.com Jul 16,2014 2:33 pm

    Hey just wanted to give you a quick heads up. The words
    in your post seem to be running off the screen in Internet explorer.
    I’m not sure if this is a format issue or something to do with browser compatibility but I figured I’d post
    to let you know. The layout look great though!
    Hope you get the issue solved soon. Cheers

  8. Reply zendesk.pueblocityschools.us Jul 19,2014 1:37 am

    WOW just what I was searching for. Came here by searching for php clean url generator

  9. Reply goji pro contra indicações Jul 26,2014 1:08 am

    I was recommended this blog by my cousin. I’m not sure whether
    this post is written by him as nobody else know such detailed
    about my problem. You’re amazing! Thanks!

  10. Reply Lanora Aug 2,2014 1:01 am

    I am regular visitor, how are you everybody?
    This post posted at this web page is genuinely good.

  11. Reply car loan for you Sep 6,2014 7:26 am

    If soe one wants to be updated with most recent
    technologies after that hee must be pay a visit this website
    andd be up to date every day.

  12. Reply promatra.zendesk.com Sep 6,2014 9:57 pm

    I like the valuable information you provide in your articles.
    I will bookmark your blog and check again here regularly.
    I am quite certain I’ll learn lots of new stuff right here!
    Good luck for the next!

  13. Reply Jodie Sep 9,2014 7:58 pm

    Heya just wanted to give you a brief heads up and let you know
    a few of the images aren’t loading correctly. I’m not sure why
    but I think its a linking issue. I’ve tried it in two different
    internet browsers and both show the same outcome.

  14. Reply business electricity prices comparison Sep 26,2014 4:48 am

    Hmm is anyone else experiencing problems with the images on this
    blog loading? I’m trying to determine if its
    a problem on my end or if it’s the blog. Any feed-back would be greatly appreciated.

  15. Reply bijoux nombril Sep 27,2014 9:19 am

    If you are going for best contents like myself, simply pay a quick visit this website daily for the reason that
    it offers feature contents, thanks

  16. Reply google.co.uk Sep 28,2014 6:29 pm

    It’s awesome for me to have a web page, which is valuable in support of
    my know-how. thanks admin

  17. Reply Business electricity Oct 1,2014 1:07 am

    Hi there, You’ve done a fantastic job. I’ll certainly digg it and personally suggest to my friends.
    I’m confident they will be benefited from this site.

  18. Reply cupless bra Oct 7,2014 4:06 pm

    My prtner and I stumbled over here different web address
    and thought I might as well check thints out. I like what I see so i am just following you.
    Look forward to checking oout your web page repeatedly.

  19. Reply somatodrol funciona mesmo Oct 8,2014 4:51 pm

    Unquestionably believe that that you stated. Your favourite
    reason appeared to be at the web the easiest thing to consider of.
    I say to you, I certainly get annoyed while other folks think about issues that they just don’t
    know about. You controlled to hit the nail upon the highest and also defined out the entire
    thing without having side effect , other folks could take a signal.
    Will probably be again to get more. Thank you

  20. Reply cheap college jerseys Oct 24,2017 12:29 am

    How to get cheap jerseys us? Tips you may used. cheap college jerseys

  21. Reply تكبير القضىب Dec 12,2017 2:30 pm

    It’s an remarkable paragraph for all the internet users; they will
    obtain advantage from it I am sure.

  22. Reply Pengeluaran Togel Hari ini Apr 27,2018 10:27 am

    “If you want to do a quick tour of the four main Disney Theme Parks,
    I’d recommend 5 days; one for each Theme Park plus
    an extra day to go back to either Epcot or the Magic Kingdom,
    both of which are difficult to do in only one day.
    Go in to your vacation knowing your must-dos and make those your highest priority.
    “There have been three major grants for the project.

  23. Reply khóa học online Mar 12,2020 8:41 pm

    Để các bạn hiểu tại sao bộ sách này lại HOT như vậy.

Leave a Reply