Question

J'ai une chaîne séparés par des virgules et je dois être en mesure de rechercher la chaîne pour les instances d'une chaîne donnée. J'utilise la fonction suivante:

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

Exemple:. Recherches isChecked('1,2,3,4', '2') si 2 est dans la chaîne et coche la case appropriée dans l'une de mes formes

Quand il vient à isChecked('1,3,4,12', '2') si, au lieu de retourner NULL il retourne TRUE, car il trouve évidemment le 2 de caractère dans 12.

Comment dois-je utiliser la fonction strpos pour les afficher uniquement les résultats corrects?

Était-ce utile?

La solution

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

Also you can use regular expressions

Autres conseils

Using explode() might be the best option, but here's an alternative:

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

Simplest way to do it may be splitting $haystack into array and compare each element of array with $needle.

Things used [except used by you like if and 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:

 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;
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top