1

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,

  • re:
  • fw:
  • #
  • read:

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:");
4
  • items of what?? use foreach in php Commented Mar 15, 2014 at 16:25
  • fairly obvious but check my update Commented Mar 15, 2014 at 16:26
  • You could use preg_match with an array for the haystack and a regex like ^re:|^fw:|^#|^read: Commented Mar 15, 2014 at 16:26
  • Did you check out my answer? Commented Mar 16, 2014 at 0:21

2 Answers 2

2
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!';
}
Sign up to request clarification or add additional context in comments.

6 Comments

on your preg_match option, could i still use strtolower ?
You don't need to. The i handles case insensitivity. Just as the i in stripos.
ah i see ok, could i put them in an array? like in my question?
If you want to, apply strtolower to $subject. It won't do anything, but you can do it.
i want to put the re: / fw: etc in an array and check the array?
|
0

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

1 Comment

You either want stripos or a third parameter for strncasecmp.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.