php - Searching for occurence of a string in a comma delimited list -
i have comma separated list , in list interested know if specific string starts in way present.
$accounting = 'acc'; $str = 'loan,k,hi,588888,acc'; if (strpos($str, $accounting) === true) { echo 'that contained accounting'; } else{ echo 'nothing found'; }
the code giving me nil found.does strpos
work in comma delimited list?.
does strpos work in comma delimited list?.
no, doesn't, because $str
not list, it's string. have convert list (=array) first:
$lst = explode(',', $str);
and search list:
if(in_array('acc', $lst)....
your wording bit unclear, if you're looking list element starts specific string, it's more complicated:
function has_element_that_starts_with($lst, $prefix) { foreach($lst $item) if(strpos($item, $prefix) === 0) // note 3 ='s homecoming true; homecoming false; }
another alternative regular expression:
if(preg_match("~(^|,){$acc}(,|$)~", $str)....
for partial strings:
if(preg_match("~(^|,){$acc}~", $str)....
php
No comments:
Post a Comment