字符串搜索中的strpos和字符串

bik*_*y77 2 php strpos

我有一个逗号分隔的字符串,我需要能够在字符串中搜索给定字符串的实例.我使用以下功能:

function isChecked($haystack, $needle) {
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return null;
    } else {
        'return 'checked="checked"';
    }
}
Run Code Online (Sandbox Code Playgroud)

示例:isChecked('1,2,3,4', '2')搜索if 2是否在字符串中并勾选我的某个表单中的相应复选框.

当谈到isChecked('1,3,4,12', '2')虽然,而不是返回NULL它返回TRUE,因为它明显地发现该字符2之内12.

我应该如何使用strpos函数才能获得正确的结果?

Emm*_*man 5

function isChecked($haystack, $needle) {
    $haystack = explode(',', $haystack);
    return in_array($needle, $haystack);
}
Run Code Online (Sandbox Code Playgroud)

您也可以使用正则表达式