PHP: Check if string contains a value in array
I was writing a a very simple script to check if a visitor was a bot. Therefore I made an array of words used by bots, and soon found out that PHP got a function to check a string in an array, but not an array in a string. So I wrote a simple function, maybe someone else needs it?
// PHP Function to check if any value in an array is in a string
//
function isin_string($string, $array) {
foreach ($array as $value) {
if (!stristr($string, $value) === FALSE) {
// value is found
return true;
} else {
// value not found
return false;
}
}
}
Or in a simpler way just implode() the array and use strrpos()
function string_in_array($string, $array) {
$array = implode(" ", $array);
if strrpos($array, $string) {
// String is found
return true;
} else {
// String was NOT found
return false;
}
}
2 Comments »
RSS feed for comments on this post. TrackBack URL
Thanks for this , Came across this , I was looking for the function to search an array for a string that you mentioned! Found it here for anyone else
function stristr_array( $haystack, $needle ) {
if ( !is_array( $haystack ) ) {
return false;
}
foreach ( $haystack as $element ) {
if ( stristr( $element, $needle ) ) {
return $element;
}
}
}
Comment by Paris Wells — February 8th, 2011 @ 22:18
Thanks, it works excellent to check if any element of an array are substrings contained in a string. Very much recommended!
Comment by RK — August 2nd, 2011 @ 17:58