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 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.
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
.
How should I use the strpos function in order to have only the correct results?
function isChecked($haystack, $needle) {
$haystack = explode(',', $haystack);
return in_array($needle, $haystack);
}
Also you can use regular expressions