如何确保域名与以下3个简单标准匹配:
- 以.com/.net结尾
不得从开始
- http://或https://
- http://www.或https://www.
我已经设法理解了正则表达式的这一部分,它与第一个标准相对应:
/.*('.com|'.net)$/
但是我不知道如何实现另外两个条件来生成一个唯一的正则表达式。
谢谢你的帮助。
用模式"不开始"有点棘手。
最清晰的方法是使用两个独立的正则表达式,一个匹配您想要的,另一个不匹配您不想要的。
但你可以在一个负面的展望中做到这一点:
/^(?!https?:'/'/(www'.)?).*('.com|'.net)$/
编辑:更正ridgerrunner 指出的断言
正则表达式解决方案很简单。只需在字符串的开头断言一个否定的前瞻性,如下所示:(带注释…(
if (preg_match('%
# Match non-http ,com or .net domain.
^ # Anchor to start of string.
(?! # Assert that this URL is NOT...
https?:// # HTTP or HTTPS scheme with
(?:www'.)? # optional www. subdomain.
) # End negative lookahead.
.* # Match up to TLD.
'. # Last literal dot before TLD.
(?: # Group for TLD alternatives.
net # Either .net
| com # or .com.
) # End group of TLD alts.
$ # Anchor to end of string.
%xi', $text)) {
// It matches.
} else {
// It doesn't match.
}
注意,由于:http://www.
是:http://
的子集,因此不必使用可选www.
的表达式。这是一个较短的版本:
if (preg_match('%^(?!https?://).*'.(?:net|com)$%i', $text)) {
// It matches.
} else {
// It doesn't match.
}
简单的正则表达式来拯救!
如果您需要确保字符串不会包含前两点,为什么不简单地使用str_replace,然后测试第一个条件呢?我认为这会更容易,当然也会更有效率。
^[a-zA-Z'.]+'.(com|net)$
这行得通吗?
如果我理解正确的话,你想查看字符串列表,找出哪些是域名。例如
http://www.a.b (F)
a.com (T)
b.net (T)
https://google.com (F)
试试这个:
if(preg_match('/^(?:http://|https://)(?:[w]{3}|)/i', $subject))
{
echo 'Fail';
}
else
{
if(preg_match('/(?:.*('.com|'.net))$/i', $subject))
{
echo 'Pass';
}
else
{
echo 'Fail';
}
}