我一直在尝试自己,并在网上搜索,写下这个正则表达式,但没有成功。
我需要验证给定的URL是来自特定域和格式良好的链接(在PHP中)。例如:
好域名:example.com
来自example.com的好网址:
糟糕的网址不是来自example.com:
一些说明: 我不关心“http”verus“https”,但如果它对你很重要,你总是假设“http” 使用这个正则表达式的代码是PHP,所以加分。
2010年更新:
Gruber添加了一个很棒的URL正则表达式:
?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))
查看他的帖子:An Improved Liberal, Accurate Regex Pattern for Matching URLs
答案 0 :(得分:7)
你必须使用正则表达式吗? PHP有许多内置函数可用于执行此类操作。
filter_var($url, FILTER_VALIDATE_URL)
会告诉您网址是否有效,
$domain = parse_url($url, PHP_URL_HOST);
会告诉你它引用的域名。
它可能比一些疯狂的正则表达式更清晰,更易于维护。
答案 1 :(得分:5)
我刺伤了它
<?php
$pattern = "#^https?://([a-z0-9-]+\.)*blah\.com(/.*)?$#";
$tests = array(
'http://blah.com/so/this/is/good'
, 'http://blah.com/so/this/is/good/index.html'
, 'http://www.blah.com/so/this/is/good/mice.html#anchortag'
, 'http://anysubdomain.blah.com/so/this/is/good/wow.php'
, 'http://anysubdomain.blah.com/so/this/is/good/wow.php?search=doozy'
, 'http://any.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
, 'http://999.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case
, 'http://obviousexample.com'
, 'http://bbc.co.uk/blah.com/whatever/you/get/the/idea'
, 'http://blah.com.example'
, 'not/even/a/blah.com/url'
);
foreach ( $tests as $test )
{
if ( preg_match( $pattern, $test ) )
{
echo $test, " <strong>matched!</strong><br>";
} else {
echo $test, " <strong>did not match.</strong><br>";
}
}
// Here's another way
echo '<hr>';
foreach ( $tests as $test )
{
if ( $filtered = filter_var( $test, FILTER_VALIDATE_URL ) )
{
$host = parse_url( $filtered, PHP_URL_HOST );
if ( $host && preg_match( "/blah\.com$/", $host ) )
{
echo $filtered, " <strong>matched!</strong><br>";
} else {
echo $filtered, " <strong>did not match.</strong><br>";
}
} else {
echo $test, " <strong>did not match.</strong><br>";
}
}
答案 2 :(得分:1)
也许:
^https?://[^/]*blah\.com(|/.*)$
编辑:
防范http://editblah.com
^https?://(([^/]*\.)|)blah\.com(|/.*)$
答案 3 :(得分:0)
\b(https?)://([-A-Z0-9]+\.)*blah.com(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)?
答案 4 :(得分:0)
!^https?://(?:[a-zA-Z0-9-]+\.)*blah\.com(?:/[^#]*(?:#[^#]+)?)?$!