「已注销」 2012-04-27 04:42
浏览 45
已采纳

如何使用PHP查找字符串是否包含特定URL?

I want to do a pattern match for certain domain names (using PHP). For example, if I am given a website URL, then I want to determine if that URL is from YouTube. The code below is what I tried, but it doesn't work (the if statement is always false). Any suggestions? Thanks ahead of time!

$website = trim( htmlentities( filter_var($_POST['website'], FILTER_SANITIZE_URL) ) );

if( preg_match("/youtube\.com/i", $website) )
{
    // do stuff
}
  • 写回答

3条回答 默认 最新

  • duanbipu7601 2012-04-27 04:45
    关注

    Your code looks fine to me...

    <?php
    
    $website = 'http://youtube.com/video?w=123455';
    
    if( preg_match("#youtube\.com#i", $website, $matches) )
    {
          print_r($matches);
    }
    

    EDIT

    Still looks like it should work:

    <?php
    
    $_POST = array();
    $_POST['website'] = 'http://youtube.com/video?w=123455';
    $website = trim( htmlentities( filter_var($_POST['website'], FILTER_SANITIZE_URL)));
    
    if( preg_match("#youtube\.com#i", $website, $matches) )
    {
          print_r($matches);
    }
    

    OUTPUT

    Array
    (
        [0] => youtube.com
    )
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘