Reputation:
I am currently using this:
if(strtolower(substr($subject,0,3)) != 're:' and strtolower(substr($subject,0,3)) != 'fw:' and strtolower(substr($subject,0,1)) != '#' and strtolower(substr($subject,0,5)) != 'read:') {
to check if the first characters of the $subject
variable are not equal to,
in uppercase or lowercase, how can i check exactly the same thing but by using items contained in an array instead?
like:
$array = array("re:", "fw:", "#", "read:");
Upvotes: 1
Views: 60
Reputation: 522076
foreach (array('re:', 'fw:', '#', 'read:') as $keyword) {
if (stripos($subject, $keyword) === 0) {
echo 'found!';
break;
}
}
or
$found = array_reduce(array('re:', 'fw:', '#', 'read:'), function ($found, $keyword) use ($subject) {
return $found || stripos($subject, $keyword) === 0;
});
or
if (preg_match('/^(re:|fw:|#|read:)/i', $subject)) {
echo 'found!';
}
or
$keywords = array('re:', 'fw:', '#', 'read:');
$regex = sprintf('/^(%s)/i', join('|', array_map('preg_quote', $keywords)));
if (preg_match($regex, $subject)) {
echo 'found!';
}
Upvotes: 2
Reputation: 173562
You can wrap the functionality of matching a string against a set of prefixes in a function:
function matches_prefixes($string, $prefixes)
{
foreach ($prefixes as $prefix) {
if (strncasecmp($string, $prefix, strlen($prefix)) == 0) {
return true;
}
}
return false;
}
And use like this:
if (!matches_prefixes($subject, ['re:', 'fw:', '#', 'read:'])) {
// do stuff
}
See also: strncasecmp
Upvotes: 0