I have an array:
$blacklist = 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?
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;}
}
return'ing to?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 will always be slower as it has to perform a linear search. This is not relevant for small arrays of course...in_array(): Clean code > micro optimizationThis 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.
}