开发者

Match Array Values to URL String

开发者 https://www.devze.com 2023-02-24 10:15 出处:网络
I have an array: $b开发者_C百科lacklist = array(\"asdf.com\", \"fun.com\", \"url.com\"); I have an input string:

I have an array:

$b开发者_C百科lacklist = array("asdf.com", "fun.com", "url.com");

I have an input string:

$input = "http://asdf.com/asdf/1234/";

I am trying to see if string $input matches any values in $blacklist.

How do I accomplish this?


Sounds like a decent use for parse_url():

<?php
    $blacklist = array("asdf.com", "fun.com", "url.com");
    $input = "http://asdf.com/asdf/1234/";

    $url = parse_url($input);

    echo (in_array($url['host'], $blacklist) ? '(FAIL)' : '(PASS)') . $url ['host'];
?>

Output:

(FAIL)asdf.com 


Using foreach is probably the best solution for what you're trying to achieve.

$blacklist = array("/asdf\.com/", "/fun\.com/", "/url\.com/");

foreach($blacklist as $bl) {
  if (preg_match($bl, $input)){return true;}
}


One way could be (but I didn't measure performance):

$san = preg_replace($blacklist, '', $input);

if($san !== $input) {
    //contained something from the blacklist
}

If the input does not contain any string from the backlist, the string will be returned unchanged.

An other, maybe better suited and definitely more efficient approach could be to extract the host part from the input and create the blacklist as associative array:

$blacklist = array(
      "asdf.com" => true,
      "fun.com" => true, 
      "url.com" => true
);

Then testing would be O(1) with:

if($blacklist[$host]) {
    //contained something from the blacklist
}


in_array is of no use, as it searches for the exact string.

You have to loop through the array, and search for it

foreach($str in $blacklist)
{
   if( stristr($input, $str ) )
    {
         //found
    }
}


This code should work:

$blacklist = array("asdf.com", "fun.com", "url.com");
$input = "http://asdf.com/asdf/1234/";
if (in_array(parse_url($input,PHP_URL_HOST),$blacklist))
  {
  // The website is in the blacklist.
  }
0

精彩评论

暂无评论...
验证码 换一张
取 消