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

时间:2011-04-29 11:31:55

标签: php strpos

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

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

示例:isChecked('1,2,3,4', '2')搜索字符串中是否有2,并勾选其中一个表单中的相应复选框。

虽然涉及到isChecked('1,3,4,12', '2'),但它不会返回NULL,而是返回TRUE,因为它显然会在2中找到字符12

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

4 个答案:

答案 0 :(得分:5)

function isChecked($haystack, $needle) {
    $haystack = explode(',', $haystack);
    return in_array($needle, $haystack);
}

您也可以使用正则表达式

答案 1 :(得分:2)

使用explode()可能是最好的选择,但这里有另一种选择:

$pos = strpos(','.$haystack.',', ','.$needle.','); 

答案 2 :(得分:0)

最简单的方法可能是将$haystack拆分为数组,并将数组的每个元素与$needle进行比较。

使用的东西[除非您使用,如果和功能]: explode() foreach strcmp trim

Funcion:

function isInStack($haystack, $needle) 
{
    # Explode comma separated haystack
    $stack = explode(',', $haystack);

    # Loop each
    foreach($stack as $single)
    {
          # If this element is equal to $needle, $haystack contains $needle
          # You can also use strcmp:
          # if( strcmp(trim($single), $needle) )
          if(trim($single) == $needle)
            return "Founded = true";        
    }
    # If not found, return false
    return null;
}

示例:

var_dump(isInStack('14,44,56', '56'));

返回:

 bool(true)

示例2:

 var_dump(isInStack('14,44,56', '5'));

返回:

 bool(false)

希望它有所帮助。

答案 3 :(得分:0)

function isChecked($haystack, $needle) 
{
    $pos = strpos($haystack, $needle);
    if ($pos === false)
    {
        return false;
    } 
    else 
    {
        return true;
    }
}