douou9786 2012-05-08 16:19
浏览 364
已采纳

如何检查文本是否包含特定域名?

I currently have this but it's not flawless:

$testcases = array(
array("I love mywebsite.com", true),
array("mywebsite.com/ is what I like", true),
array("www.mywebsite.com is my website", true),
array("Check out www.mywebsite.com/", true),
array("... http://mywebsite.com ...", true),
array("... http://mywebsite.com/ ...", true),
array("... http://www.mywebsite.com ...", true),
array("... http://www.mywebsite.com/ ...", true),
array("I like commas and periods. Just like www.mywebsite.com, they do it too!", true),
array("thisismywebsite.com is a lot better", false),
array("The URL fake.mywebsite.com is unknown to their server", false),
array("Check out http://redirect.mywebsite.com/www.ultraspammer.com", false)
);

function contains_link($text) {
return preg_match("/(https?:\/\/(?:www\.)?|(?:www\.))mywebsite\.com/", $text) > 0;
}

foreach ($testcases as $case) {
echo $case[0] . "=".(contains_link($case[0]) ? "true" : "false") . " and it should be " . ($case[1] ? "true" : "false") . "<br />";
}

Output:

I love mywebsite.com=false and it should be true
mywebsite.com/ is what I like=false and it should be true
www.mywebsite.com is my website=true and it should be true
Check out www.mywebsite.com/=true and it should be true
... http://mywebsite.com ...=true and it should be true
... http://mywebsite.com/ ...=true and it should be true
... http://www.mywebsite.com ...=true and it should be true
... http://www.mywebsite.com/ ...=true and it should be true
I like commas and periods. Just like www.mywebsite.com, they do it too!=true and it should be true
thisismywebsite.com is a lot better=false and it should be false
The URL fake.mywebsite.com is unknown to their server=false and it should be false
Check out http://redirect.mywebsite.com/www.ultraspammer.com=false and it should be false
  • 写回答

3条回答 默认 最新

  • doujiang1001 2012-05-08 16:23
    关注

    An alternative to regex: parse_url()

    $url = parse_url($text);
    if($url['host'] == 'www.mywebsite.com' || $url['host'] == 'mywebsite.com')
    

    UPDATE:

    Assuming that $text can have a lot of domains,use strstr() instead.

    if(strstr($text,"mywebsite.com") !== FALSE)
    

    UPDATE 2:

    function contains_link($text) {
            return preg_match("/(^(https?:\/\/(?:www\.)?|(?:www\.))?|\s(https?:\/\/(?:www\.)?|(?:www\.))?)mywebsite\.com/", $text);
    }
    

    and:

      contains_link("AAAAAAA http://mywebsite.com"); //1
      contains_link("foo BAaa http://www.mywebsite.com"); //1
      contains_link("abc.com www.mywebsite.com"); // 1
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 MATLAB怎么通过柱坐标变换画开口是圆形的旋转抛物面?
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题
  • ¥15 Visual Studio问题
  • ¥20 求一个html代码,有偿