0

我很简单formurl应该在哪里输入,但我想使用更好的或者检查它regx是否anything else有效的 url。

我知道已经发布了无数关于它的问题,但是其中大多数甚至在域和其他失败之前就已经很老了,TLDs以防万一ftp//https//

我希望我能得到真正能够涵盖这种url计划的答案

google.com
www.google.com
http//google.com
http//www.google.com
https://google.com
https://www.google.com
ftp://google.com

〜感谢并再次抱歉发布重复的问题,但只是为了尽可能获得更新的答案。

4

3 回答 3

3

这可能不是正则表达式的工作,而是您选择的语言的现有工具。 正则表达式不是你在碰巧涉及字符串的每个问题上挥舞的魔杖。您可能希望使用已经编写、测试和调试过的现有代码。

在 PHP 中,使用该parse_url函数。

Perl:URI模块

红宝石:URI模块

.NET:“Uri”类

于 2013-10-17T21:37:41.437 回答
2

的用法parse_url()如下,但@wrikken 提出了一种更好的方法来简单地验证 URL 是否“有效” filter_var()parse_url()只是将指定的 URL 字符串解析为其组成部分,并且显然不会返回false值,除非 URL 被灾难性地破坏。

filter_var()足够敏感,它会检测到像域名中使用的下划线这样的次要内容。

var_dump(
  filter_var(
    'http://stack-overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105',
     FILTER_VALIDATE_URL
  )
);

//output: string(113) "http://stack-overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105"

var_dump(
  filter_var(
    'http://stack_overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105',
    FILTER_VALIDATE_URL
  )
);

//output: bool(false)

parse_url()最好保留提取您已经知道有效的 URL 部分:

var_dump(parse_url('http://stackoverflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105'));

输出:

array(5) {
  ["scheme"]=>
  string(4) "http"
  ["host"]=>
  string(17) "stackoverflow.com"
  ["path"]=>
  string(50) "/questions/19437105/using-regx-how-to-validate-url"
  ["query"]=>
  string(12) "noredirect=1"
  ["fragment"]=>
  string(24) "comment28819663_19437105"
}

或者怎么样:

于 2013-10-17T21:59:05.247 回答
0

正则表达式既方便又昂贵,但用于验证 URL:

^((ht|f)tp(s?)\:\/\/|~\/|\/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?\/?(\w+\.[\w]{3,4})?((\?\w+=\w+)?(&\w+=\w+)*)?
于 2013-10-17T21:05:30.980 回答