0

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
}
John Anderson
  • 1,075
  • 5
  • 21
  • 25
  • 1
    How is that not working? – sberry Apr 27 '12 at 04:44
  • take a look on the link http://php.net/manual/en/function.preg-match.php – jogesh_pi Apr 27 '12 at 04:46
  • 1
    Possible Duplicates: http://stackoverflow.com/questions/2129443/any-preg-match-to-check-if-a-url-is-a-youtube-vimeo-dailymotion-video-link / http://stackoverflow.com/questions/4977233/regexp-to-find-youtube-url-strip-off-parameters-and-return-clean-video-url / http://stackoverflow.com/questions/1383073/php-validate-youtube-url / http://stackoverflow.com/questions/8027023/regex-php-auto-detect-youtube-image-and-regular-links – anonymous Apr 27 '12 at 04:48
  • 1
    So, if `$website` was "http://www.google.com/?q=youtube.com", what would your expected behavior be? Could that ever happen? Perhaps something a little more robust like `parse_url()` and checking the "host" key could be more accurate. – Cᴏʀʏ Apr 27 '12 at 04:50
  • I just updated the code to be more specific. The URL is coming from a form. Maybe it is the way I sanitize the URL? – John Anderson Apr 27 '12 at 04:51

3 Answers3

4

You could use PHP's parse_url function. eg.

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

This will give you the hostname. You can then use it for your checks

if(parse_url($POST['website'], PHP_URL_HOST) == 'youtube.com') // do something
Anirudh
  • 388
  • 3
  • 9
1

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
)
sberry
  • 128,281
  • 18
  • 138
  • 165
-1
 if(strpos("youtube.com", $website) )
 {

   // do stuff
 }
Ravi Jethva
  • 1,931
  • 2
  • 11
  • 12