【问题标题】:How do I use PHP to find if a string contains a specific URL?如何使用 PHP 查找字符串是否包含特定 URL?
【发布时间】:2012-04-27 04:42:39
【问题描述】:

我想对某些域名进行模式匹配(使用 PHP)。例如,如果给我一个网站 URL,那么我想确定该 URL 是否来自 YouTube。下面的代码是我尝试过的,但它不起作用(if 语句总是错误的)。有什么建议么?提前谢谢!

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

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

【问题讨论】:

标签: php preg-match


【解决方案1】:

您可以使用 PHP 的 parse_url 函数。例如。

parse_url($POST['website'], PHP_URL_HOST);

这将为您提供主机名。然后您可以将其用于支票

if(parse_url($POST['website'], PHP_URL_HOST) == 'youtube.com') // do something

【讨论】:

    【解决方案2】:

    你的代码在我看来不错...

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

    编辑

    看起来它应该可以工作:

    <?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);
    }
    

    输出

    Array
    (
        [0] => youtube.com
    )
    

    【讨论】:

      【解决方案3】:
       if(strpos("youtube.com", $website) )
       {
      
         // do stuff
       }
      

      【讨论】:

        猜你喜欢
        • 2012-10-19
        • 1970-01-01
        • 2022-01-02
        • 2011-10-06
        • 2014-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多