Make string url ready
Here is a simple way to convert text so it can be used as a part of url.
$myText = " This Is Some/Text with tab\nnew line and lot of spaces\n";
// This Is Some Text with tab
//new line and lot of spaces
//
We will transform our text to lowercase
$myUrl = strtolower($myText);
// this is some text with tab
//new line and lot of spaces
//
Remove spaces, new line characters from begining and end
$myUrl = trim($myUrl);
//this is some text with tab
//new line and lot of spaces
Replace tabs, spaces and backslashes with dashes.
$myUrl = preg_replace('/[\s]+|\t|\n|\r|\//', "-", $myUrl);
//this-is-some-text-with-tab-new-line-and-lot-of-spaces
Now do everything in one line
$myUrl=preg_replace('/[\s]+|\t|\n|\r|\//', "-",strtolower(trim($myText)));
Here is the same thing for javascript.
Written by Michał Kowalkowski
Related protips
7 Responses
why not to use buildin urlencode() for php and encodeURI() or encodeURIComponent() for js?
What an author is trying to achieve is a slug-like url
@spinache do you really think this solution can make a valid URL out of text? Try this: "some piece of text with ? and & andagain?"
@dimasmagadan You raise a valid point. Functions you mention are a good way to encode string to be used in url.
Why I use my method is because I like more control over how the url will look like.
I think "this-is-some-text-with-tab-new-line-and-lot-of-spaces" is a little more elegant than "+This+Is+Some%2FText+with%09tab%0Anew+line+and+lot+of+++++++spaces%0A".
Also by using regex you can easily customize my method and specify how you want it to handle special characters like ? & or dots.
@michalkow than your solution lacks two things: regexps to handle all special chars and a solution to transform your converted URL back to text.
wouldn't it be just as easy to call
$url = filter_var($string, FILTER_SANITIZE_URL);
@xero You are right - it would be easier. I can only say to that, what I said to "dimasmagadan" in my post before.
If you do not care how the url will look like, then functions you proposed are valid and much easier solution.