字符串以一组定义的单词开头

时间:2015-02-10 22:30:36

标签: php arrays string

如何知道给定的字符串是否以一组不确定的单词开头?

$allowed = array("foo", "bar");

伪代码:

$boolean = somefunction($allowed,'food');

$ boolean应为TRUE

4 个答案:

答案 0 :(得分:2)

function doesStringStartWith($string, $startWithOptions)
{
    foreach($startWithOptions as $option)
    {
        if(substr($string, 0, strlen($option)) == $option) // comment this for case-insenstive
        // uncomment this for case-insenstive: if(strtolower(substr($string, 0, strlen($option))) == strtolower($option))
        {
            return true;
        }
    }
    return false;
}

$result = doesStringStartWith('food', array('foo', 'bar'));

答案 1 :(得分:1)

function somefunction($allowed, $word) {
    $result = array_filter(
        $allowed,
        function ($value) use ($word) {
            return strpos($word, $value) === 0;
        }
    );
    return (boolean) count($result);
}

$boolean = somefunction($allowed,'food');

答案 2 :(得分:0)

如果您知道所有前缀的长度相同,则可以执行此操作:

if ( in_array( substr($input,0,3), $allowed ) {
    // your code
}

答案 3 :(得分:0)

我提出了以下功能:

function testPos($allowed,$s) {
    $a = 0;
    while($a < count($allowed)) {
        if(strpos($s,$allowed[$a]) === 0) {
            return true;
        }
        $a++;
    }
}

现在你可以尝试:

$allowed = array('foo','bar');
echo testPos($allowed,'food');