The perfect PHP clean url generator
via: http://cubiq.org/the-perfect-php-clean-url-generator/12
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
toAsciifunction we can convert a string like “Hi! I’m the title of your page!” tohi-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 bea-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. The piñ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 for pinata. 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 candyThere’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 geti-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 exampleI’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?
voce del verbo dismagare
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take arms against a sea of troubles,
And by opposing end them? To die: to sleep;
No more; and by a sleep to say we end
The heart-ache and the thousand natural shocks
That flesh is heir to, 'tis a consummation
Devoutly to be wish'd. To die, to sleep;
To sleep: perchance to dream: ay, there's the rub;
For in that sleep of death what dreams may come
When we have shuffled off this mortal coil,
Must give us pause: there's the respect
That makes calamity of so long life;
For who would bear the whips and scorns of time,
The oppressor's wrong, the proud man's contumely,
The pangs of despised love, the law's delay,
The insolence of office and the spurns
That patient merit of the unworthy takes,
When he himself might his quietus make
With a bare bodkin? who would fardels bear,
To grunt and sweat under a weary life,
But that the dread of something after death,
The undiscover'd country from whose bourn
No traveller returns, puzzles the will
And makes us rather bear those ills we have
Than fly to others that we know not of?
Thus conscience does make cowards of us all;
And thus the native hue of resolution
Is sicklied o'er with the pale cast of thought,
And enterprises of great pith and moment
With this regard their currents turn awry,
And lose the name of action.--Soft you now!
The fair Ophelia! Nymph, in thy orisons
Be all my sins remember'd.
questo è il nodo: se sia più nobil animo
sopportar le fiondate e le frecciate
d'una sorte oltraggiosa,
o armarsi contro un mare di sciagure,
e contrastandole finir con esse.
Morire... addormentarsi: nulla più.
E con un sonno dirsi di por fine
alle doglie del cuore e ai mille mali
che da natura eredita la carne.
Questa è la conclusione
che dovremmo augurarci a mani giunte.
Morir... dormire, e poi sognare, forse...
Già, ma qui si dismaga l'intelletto:
perché dentro quel sonno della morte
quali sogni ci possono venire,
quando ci fossimo scrollati via
da questo nostro fastidioso involucro?
Ecco il pensiero che deve arrestarci.
Ecco il dubbio che fa così longevo
il nostro vivere in tal miseria.
Se no, chi s'indurrebbe a sopportare
le frustate e i malanni della vita,
le angherie dei tiranni,
il borioso linguaggio dei superbi,
le pene dell'amore disprezzato,
le remore nell'applicar le leggi,
l'arroganza dei pubblici poteri,
gli oltraggi fatti dagli immeritevoli
al merito paziente,
quand'uno, di sua mano, d'un solo colpo
potrebbe firmar subito alla vita
la quietanza, sul filo d'un pugnale?
E chi vorrebbe trascinarsi dietro
questi fardelli, e gemere e sudare
sotto il peso d'un'esistenza grama,
se il timore di un "che" dopo la morte
- quella regione oscura, inesplorata,
dai cui confini non v'è viaggiatore
che ritorni - non intrigasse tanto
la volontà, da indurci a sopportare
quei mali che già abbiamo,
piuttosto che a volar, nell'aldilà,
incontro ad altri mali sconosciuti?
Ed è così che la nostra coscienza
ci fa vili; è così che si scolora
al pallido riflesso del pensiero
il nativo colore del coraggio,
ed alte imprese e di grande momento,
a cagione di questo, si disviano
e perdono anche il nome dell'azione.
(Vede Ofelia)
Ma zitto, adesso!... La leggiadra Ofelia!
Ninfa, nelle tue preci
rammemoràti siano i miei peccati.
distruzione a mantova

da sinistra a destra: l'interprete, neil gaiman, la mia sorellina delirio, io e sogno posterizzato a mo' di sfondo.. un grazie grande come una casa al team di www.neilgaimania.it per la foto.
è interessante notare il rapporto fra Distruzione e Delizia/Delirio. La distruzione è il prodotto del cambiamento, che ha portato Delizia attraverso la distruzione della sua vecchia identità e nella creazione di una nuova, Delirio appunto. Distruzione inoltre, come viene narrato nel fumetto, prova a diventare un'artista. Nonostante la sua arte sia imperfetta, egli è rinvigorito dalla libertà di creare un po' proprio come Gaiman.. [...]
vaor€ della cultura
[...] Ero di umore nerissimo. Umore che non migliorò affatto quando uno dei due uomini, nel prendere i soldi, chiese innocentemente: - Scusi, signore, cosa significa mac... machiavellico?
- è un temine spagnolo che sta per impicciati degli affari tuoi - risposi seccato. Sulla navetta mi domandai quanto ricco sarei dovuto diventare per comprare un po' di privacy.
depressione cosmica

Simon si alzò in piedi e urlò: - Ma perché? Perché? Perché? Non sapeva quali tormenti e angosce avrebbe fatto patire, senza nessun motivo, a miliardi di miliardi di esseri viventi?
- Certo - disse Bingo.
- E allora perché? - urlò Simon Wagstaff. - Perché? Perché? Perché?
Il vecchio Bingo bevve un bicchiere di birra, ruttò e rispose: - Perché no?
indicativo del mio stato d'animo perenne. non servono altre spiegazioni.

