tags:

views:

87

answers:

4

I have an array and a variable, 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) {
 ...        
}
A: 

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.

Oren
A: 

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.

jensgram
If you swap `if (strpos($entry, $needle) !== false) {` for `if (strpos($needle, $entry) !== false) {` in your first answer (ideally renaming `$needle`, e.g. to `$variable`), this is a perfect answer to the question! The question is if [any of] the array elements are in the variable, not vice versa. :)
pinkgothic
@pinkgothic You're right. Edited.
jensgram
+3  A: 
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.)

pinkgothic
+1  A: 

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');   
}
Tom Haigh
Ooh, that's an interesting trick - I like out of the box thinking. Though `$count` would fail to be accurate if one of the array elements was a subset of another, or overlapped, right? Mind, that's of course only relevant if you need an exact number of matches, and I doubt that's the case here. [I really, really need to stop reaching my daily upvoting limit in the first five minutes of SO. c_c]
pinkgothic
@pinkgothic: Yeah you are right, you would get a smaller count, because subsequent searches would be on the modified string.
Tom Haigh
Still, this is pretty awesome! I'm committing it to memory. Thank you for sharing. :)
pinkgothic