PHP检查数组中是否包含字符串的前几个字符

时间:2014-03-15 16:22:21

标签: php arrays

我目前正在使用这个:

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:') {

检查$subject变量的第一个字符是否不等于

  • 重新:
  • FW:
  • 读:

大写或小写,我如何检查完全相同的东西,而不是使用数组中包含的项目?

像:

$array = array("re:", "fw:", "#", "read:");

2 个答案:

答案 0 :(得分:2)

foreach (array('re:', 'fw:', '#', 'read:') as $keyword) {
    if (stripos($subject, $keyword) === 0) {
        echo 'found!';
        break;
    }
}

$found = array_reduce(array('re:', 'fw:', '#', 'read:'), function ($found, $keyword) use ($subject) {
    return $found || stripos($subject, $keyword) === 0;
});

if (preg_match('/^(re:|fw:|#|read:)/i', $subject)) {
    echo 'found!';
}

$keywords = array('re:', 'fw:', '#', 'read:');
$regex    = sprintf('/^(%s)/i', join('|', array_map('preg_quote', $keywords)));

if (preg_match($regex, $subject)) {
    echo 'found!';
}

答案 1 :(得分:0)

您可以将函数字符串的功能与函数中的一组前缀相匹配:

function matches_prefixes($string, $prefixes)
{
    foreach ($prefixes as $prefix) {
        if (strncasecmp($string, $prefix, strlen($prefix)) == 0) {
            return true;
        }
    }
    return false;
}

并像这样使用:

if (!matches_prefixes($subject, ['re:', 'fw:', '#', 'read:'])) {
    // do stuff
}

另请参阅:strncasecmp