PHP Is Array Item In Variable
I have an array and a vari开发者_开发技巧able, I want to check if any of the array items occur in the variable. I presume I somehow use strstr()?
Example:
$bad = array('google.com', 'facebook.com', 'myspace.com');
$ref = $_SERVER['HTTP_REFERER'];
if(ANY OF $bad IS IN $ref) {
...
}
foreach ($array as $value) {
if (strpos($variable, $value) !== false) {
// yep, this array element exists in your variable, do what you want here
}
}
(strpos() is a better choice than strstr(), it's less resource-heavy.)
You could do it like this, but it is a bit of a cheat. str_ireplace()
will take an array of search values, and also will tell you how many replacements it did, so if it did any replacements you know you have a match.
<?php
$bad = array('google.com', 'facebook.com', 'myspace.com');
$ref = $_SERVER['HTTP_REFERER'];
str_ireplace($bad, '', $ref, $count);
if ($count > 0) {
die ('bad');
}
You should use strpos if you only want to determine if the variable exists, but you don't need to return part of the string.
If you need substring matching for your referers (e.g., match 'three' in '...three...'):
$array = array('one', 'two', 'three', ...);
$val = '...three...';
foreach ($array as $entry) {
if (strpos($val, $entry) !== false) {
print 'Look ma, I found it!';
}
}
If not (i.e., you are looking for exact matches), you can just;
$array = array('one', 'two', 'three', ...);
$needle = 'three';
if (in_array($needle, $array)) {
print 'Look ma, I found it!';
}
Edited according to @pinkgothic's (correct) comment.
精彩评论