当url不允许列表时显示错误?

时间:2014-10-15 14:08:38

标签: php regex list url

如果$ text不允许列表打印错误。不知道怎么做

$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
$text = 'this is my url www.abcd.com/index.php?page=home';

4 个答案:

答案 0 :(得分:0)

试试这个

$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');

if ( !in_array('your-domain-name', $allowedDomains) {
    echo 'show your error here';
} else {
    echo  'do what ever you want here';
}

答案 1 :(得分:0)

以下是另一种方法:使用域列表创建正则表达式,然后使用它来测试文本字符串。

$allowedDomains = array('www.test1.com', 'www.test2.co.uk', 'test3.com');
# concatenate the allowed domains with | and surround with brackets so the regex will
# match any of the array items
# i.e. $regex is (www.test1.com|www.test2.co.uk|test3.com)
$regex = "(" . implode("|", $allowedDomains) . ")";

# a couple of test strings
$texts = array('this is my url www.abcd.com/index.php?page=home',
         'my home page is www.test3.com');

foreach ($texts as $t) {
    if (preg_match("/$regex/", $t)) {
        echo "Found a match! $t\n";
    }
    else {
        echo "No match found: $t\n";
    }
}

输出:

  

No match found: this is my url www.abcd.com/index.php?page=home

     

Found a match! my home page is www.test3.com

答案 2 :(得分:0)

我已经为您编写了一个功能,允许您根据需要添加/删除域名和/或域名扩展名,考虑到不是每个人都输入“http(s)”和/或“www”进入他们的域名搜索以及域名背后可能存在哪种信息的不可预测性:

<?php

function testDomain($domain){

    //Set domain names
    $arrDomainNames = array("test1","test2","test3");

    //Set domain extensions like .com .co .info
    //Do NOT add .co.uk! .uk is taken care of in the regex
    $arrDomainExt = array("com","co");

    $cntDomainNames = count($arrDomainNames);
    $cntDomainExt = count($arrDomainExt);
    $i = 0;
    $y = 0;

    $DomNames = "";
    $DomExt = "";

    foreach($arrDomainNames as $value){
        if($i == $cntDomainNames - 1){
            $DomNames .= $value;
        } else {
            $DomNames .= $value ."|";
        }
        $i++;
    }

    unset($value);

    foreach($arrDomainExt as $value){
        if($y == $cntDomainExt - 1){
            $DomExt .= $value;
        } else {
            $DomExt .= $value ."|";
        }
        $y++;
    }

    unset($value);

    $pattern = "/((((http|ftp|https)+(:)+(\/{2})))?+(www\.)?(((". $DomNames .")+\.)+(". $DomExt .")+(\.uk)?(:[0-9]+)?((\/([~0-9a-zA-Z\#\+\%@\.\/_-]+))?(\?[0-9a-zA-Z\+\%@\/&\[\];=_-]+)?)?))\b/imu";
    if(preg_match($pattern, $domain)){
        echo "Domain match!<br />";
    } else {
        echo "Domain not match!<br />";
    }
}

testDomain("www.test1.com"); //match
testDomain("test1.com"); //match
testDomain("http://www.test1.co.uk"); //match
testDomain("test1.com/info.php?who=you"); //match
testDomain("www.google.com"); //no match

?>

答案 3 :(得分:0)

如何使用

$arrDomainNames = array("test1.com","test2.org","test3.co.uk","test3.net");

$arrDomainExt = array("com","co");