简体   繁体   English

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

[英]strpos and string in string searches

I have a comma delimited string and I need to be able to search the string for instances of a given string.我有一个逗号分隔的字符串,我需要能够在字符串中搜索给定字符串的实例。 I use the following function:我使用以下 function:

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

Example: isChecked('1,2,3,4', '2') searches if 2 is in the string and ticks the appropriate checkbox in one of my forms.示例: isChecked('1,2,3,4', '2')搜索2是否在字符串中,并在我的 forms 之一中勾选相应的复选框。

When it comes to isChecked('1,3,4,12', '2') though, instead of returning NULL it returns TRUE , as it obviously finds the character 2 within 12 .但是,当涉及到isChecked('1,3,4,12', '2')时,它不是返回NULL而是返回TRUE ,因为它显然在12中找到了字符2

How should I use the strpos function in order to have only the correct results?我应该如何使用 strpos function 才能获得正确的结果?

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

Also you can use regular expressions你也可以使用正则表达式

Using explode() might be the best option, but here's an alternative:使用 explode() 可能是最好的选择,但这里有一个替代方案:

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

Simplest way to do it may be splitting $haystack into array and compare each element of array with $needle .最简单的方法可能是将$haystack拆分为数组并将数组的每个元素与$needle进行比较。

Things used [except used by you like if and function]: explode() foreach strcmp trim使用的东西[除了你喜欢的 if 和 function]: 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;
}

Example:例子:

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

Returns:回报:

 bool(true)

Example 2:示例 2:

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

Returns:回报:

 bool(false)

Hope it helps.希望能帮助到你。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM