Take a string such as:
In C#: How do I add "Quotes" around string in a comma delimited list of strings?
and convert it to:
in-c-how-do-i-add-quotes-around-string-in-a-comma-delimited-list-of-strings
Requirements:
- Separate each word by a dash and remove all punctuation (taking into account not all words are separated by spaces.)
- Function takes in a max length, and gets all tokens below that max length. Example:
ToSeoFriendly("hello world hello world", 14)
returns"hello-world"
- All words are converted to lower case.
On a separate note, should there be a minimum length?
Here is my solution in C#
Here's a solution for php:
usage:
Unless you need the uris to be typable, they don't need to be small. But you should specify a maximum so that the urls work well with proxies etc.
This is close to how Stack Overflow generates slugs:
A slightly cleaner way of doing this in PHP at least is:
Might as well do the
trim()
at the start so there is less to process later and the full replacement is done with in thepreg_replace()
.Thxs to cg for coming up with most of this: What is the best way to clean a string for placement in a URL, like the question name on SO?
I would follow these steps:
replace multiple hyphens by one hyphen(not necessary as thepreg_replace()
function call already prevents multiple hyphens)So, all together in a function (PHP):
Another season, another reason, for choosing Ruby :)
That's all.