a-viza
Last Updated: February 25, 2016
·
899
· michalkow

Make string url ready

php

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.

7 Responses
Add your response

2523

why not to use buildin urlencode() for php and encodeURI() or encodeURIComponent() for js?

over 1 year ago ·
2526

What an author is trying to achieve is a slug-like url

over 1 year ago ·
2527

@spinache do you really think this solution can make a valid URL out of text? Try this: "some piece of text with ? and & andagain?"

over 1 year ago ·
2543

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

over 1 year ago ·
2547

@michalkow than your solution lacks two things: regexps to handle all special chars and a solution to transform your converted URL back to text.

over 1 year ago ·
2828

wouldn't it be just as easy to call

$url = filter_var($string, FILTER_SANITIZE_URL);
over 1 year ago ·
2831

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

over 1 year ago ·