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
}
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
)
if(strpos("youtube.com", $website) )
{
// do stuff
}
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