preg_match Issue with "or", "and" in PHP


preg_match Issue with "or", "and" in PHP

我使用POST方法从输入中获取URL信息。

可能网址:

  • 交货。1: http://host.com
  • 交货。2: http://www.host.com
  • 交货。3: www.host.com
  • 交货。4: host.com

我想,url不开始"http://www." "www." 只开始 "http://"。我用了那个代码块,但是没有成功。

preg_match(("/(^http:'/'/www'.)|(^www'.)/")), $url_data);

你的正则表达式可以简化一些:

preg_match("/^http://(?!www'.)/", $url_data);

这将在字符串的开头查找http://,后面不跟着(?!) www.。下面是一个关于Regexpal的例子。

^http:'/'/(?!www'.).*$

应该做。

deme here: http://regex101.com/r/bA1rR4

如果你不想有任何子域

使用this:

^http:'/'/(?!www'.)'w+'.'w+$

demo here: http://regex101.com/r/jY0aP6

第二更新

^http:'/'/(?!www'.)'w+'.'w+(?:'/.*)?$
http://regex101.com/r/vO5xV4

允许扩展名

之后的任何内容

这里可以使用负正向正则表达式。以"http://"开头的表达式也可以满足不以"www."开头的表达式。

最后你有两个条件要满足

1. 以"http://"开头
2. 不以"http://www."

开头

下面的preg_match函数就可以了:

preg_match("^http:'/'/(?!www'.).*$", $url_data);