Reputation: 15960
I have a text-box, where I will be getting URL
URLs can be entered in any of the following format:
example.com
www.example.com
http://example.com
http://www.example.com
example.com/
www.example.com/
http://example.com/
http://www.example.com/
I need to convert them to single
http://example.com/
How can I do it, there must be simple way round to do it, right?
Upvotes: 1
Views: 59
Reputation: 13972
Try using a regular expression with some optional parts. It seems the optional parts of your string are...
Here is some code...
$text = "http://example.com";
if (preg_match('%^(http://)?(www\.)?(.*?)(/)?$%i', $text, $regs)) {
$result = $regs[3];
// $result now contains example.com - add whatever wrapper you need to it
}
Upvotes: 1
Reputation: 5824
If you really only expect this few variations you could solve this, with a regex. For example
<?php
// $input = The data you retrieved
$output = preg_replace('#^(?:http://)?(?:www\.)?(.*?)/?$#', 'http://$1/', $input);
echo $output;
I didn't test it, but should work.. If not, let me know :)
** Edit ** Just tested it. Works fine. At least for the formats you specified.
Upvotes: 1