开发者

formatting URL to single type

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/开发者_Python百科

 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?


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.


Try using a regular expression with some optional parts. It seems the optional parts of your string are...

  • http://
  • www.
  • trailing /

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜