John Anderson
John Anderson

Reputation: 1085

How do I use PHP to find if a string contains a specific 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
}

Upvotes: 0

Views: 1723

Answers (3)

Anirudh
Anirudh

Reputation: 388

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

Upvotes: 4

sberry
sberry

Reputation: 132138

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
)

Upvotes: 1

Ravi Jethva
Ravi Jethva

Reputation: 2031

 if(strpos("youtube.com", $website) )
 {

   // do stuff
 }

Upvotes: -1

Related Questions