The following should work:
function spamCheck($input){
$flags = array('cialis', 'viagra', 'erection', 'pharmac', 'porn', 'anal', 'bondage', 'insurance', 'ringtone', 'poker', 'casino', 'gambl', 'whore', 'nipple', 'shit', 'realt', 'shemale', 'valium');
$input = explode(' ', $input);
foreach($input as $word){
$word = trim($word, '",.!?\';:*');
foreach($flags as $flag){
if(strpos(strtolower($word), $flag) !== false){
return $word;
}
}
}
return false;
}
$spam = spamCheck("Download free ringtones for your mobile phone.");
print($spam); // will print "ringtones"
Read more about the return values of strpos.
Update: The regex equivalent of your function:
function spamCheck($input){
$flags = array('cialis', 'viagra', 'erection', 'pharmac', 'porn', 'anal', 'bondage', 'insurance', 'ringtone', 'poker', 'casino', 'gambl', 'whore', 'nipple', 'shit', 'realt', 'shemale', 'valium');
$pattern = "/\\b[a-z]*(?:".implode("|", $flags).")[a-z]*\\b/i";
if(preg_match($pattern, $input, $matches)){
return $matches[0];
}
return false;
}