PHP / PDO - 检查URL是否包含特定的域列表

时间:2016-05-10 13:01:38

标签: php mysql pdo

我有一个数组中的域列表,例如

$notAllowedWebsites = array('google.com','yahoo.com','facebook.com');

现在我有一个MySQL数据库,其中包含一个充满网址的列,例如

  1. facebook.com/testpage
  2. google.com/search
  3. bbc.co.uk/news/going-to-the-sea
  4. ft.com/big-success
  5. google.com/time
  6. 现在我想从url中存在域的上表中提取上述URL。换句话说,我想提取:  1. facebook.com/testpage  2. google.com/search  3. google.com/time

    这是我的代码:

    foreach($notAllowedWebsite as $notAllowedWebsite){
        $sqlQueryBusinessWebsite = $dbh->prepare("SELECT business_website FROM client_table WHERE business_website = :business_website");
        $sqlQueryBusinessWebsite->execute(array(':business_website'=>$notAllowedWebsite));
        $sqlResultBusinessWebsite = $sqlQueryBusinessWebsite->fetch();
        $businessWebsiteDB = $sqlResultBusinessWebsite['business_website'];
    }
    

    我不确定如何修改此行$sqlQueryBusinessWebsite = $dbh->prepare("SELECT business_website FROM client_table WHERE business_website = :business_website");以检查网址是否存在。

    感谢。

3 个答案:

答案 0 :(得分:0)

使用LIKE子句:

foreach($notAllowedWebsite as $notAllowedWebsite){
    $sqlQueryBusinessWebsite = $dbh->prepare("SELECT business_website FROM client_table WHERE business_website LIKE :business_website");
    $sqlQueryBusinessWebsite->execute(array(':business_website'=>'%'.$notAllowedWebsite.'%'));
    $sqlResultBusinessWebsite = $sqlQueryBusinessWebsite->fetch();
    $businessWebsiteDB = $sqlResultBusinessWebsite['business_website'];
}

答案 1 :(得分:0)

使用Regular Expression将是最佳解决方案

SELECT business_website FROM business_website WHERE business_website RLIKE '(?=.*facebook)(?=.*yahoo)'

答案 2 :(得分:0)

虽然我确信有更简洁的方法,但以下内容将使所有包含来自禁止列表的域名的网站获得:

CREATE TABLE `banned_sites` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `domain` VARCHAR(255) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
);

CREATE TABLE `entries` (
    `id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
    `website` VARCHAR(255) NOT NULL DEFAULT '0',
    PRIMARY KEY (`id`)
);

insert into banned_sites (domain) values ('facebook.com'), ('yahoo.com'), ('google.com');
insert into entries (website) values ('http://www.facebook.com/thisisatest'), ('http://www.msn.com'), ('http://google.com'), ('yahoo.com');

然后你可以这样做:

select e.* from entries e inner join banned_sites bs on (e.website like concat('%', concat(bs.domain, '%')))

SQLFiddle现在不工作,否则我会告诉你它正在工作。