3

I have a string in php and I want to convert it into a URL,Basically I am taking input from the user so I am not sure either he write http://www.google.com or just www.google.com or maybe just google.com, In either cases I have to show him the URL link in an anchor tag. I am looking for any PHP function that can do this, Otherwise I have to manually search for http and other If else condition will surely gonna waste my time,If there is no function I would be more than happy to write one and make it open to the community. EDIT: Another thing is the best way to write HTML in PHP, I mean is it good if we use echo' long HTML Forms' etc any solution Thanks

3
  • 2
    if you put any of this string as a source of url it will work. also remember that subdomains don't use www on start. if you want to have http:// on start check if string contains http://. if not add this if yes don't Commented Aug 27, 2013 at 9:04
  • @Fixus sounds like a good solution , can you see the update I made to question thanks Commented Aug 27, 2013 at 9:07
  • there is no best way it dependes on your solution. i never echo it i return in after parsing in template engine. Commented Aug 27, 2013 at 9:36

4 Answers 4

7

you can still use parse_url function

$parsed = parse_url($urlStr);
if (empty($parsed['scheme'])) {
    $urlStr = 'http://' . ltrim($urlStr, '/');
}

about writing html with PHP, it's okay to use echo function, just make sure you escape the double quotes with backslash

Sign up to request clarification or add additional context in comments.

Comments

2

I think you are looking for parse_url

http://php.net/manual/en/function.parse-url.php

1 Comment

thank you but this is not what I am looking for, it just parses your string
0

Use the substr() functoin for existence of HTTP and if not present add HTTP, put the string as Href in the anchor tag.Surely gonna work

2 Comments

what if the user put some link to an HTTPS site?
@user1765876 you have to take care of both conditions
0

You can use parse_url() who will try to parse input into part. And you just have to check if "scheme" is here to know how to complete url.

If you want to validate input, you can use filter_var() with FILTER_VALIDATE_URL option

filter_var($input, FILTER_VALIDATE_URL) ) ? echo "Valid url" : echo "invalid url"; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.