galvin Posted September 19, 2012 Share Posted September 19, 2012 Say you have a simple string that has just numbers and commas, like... $numbers="12,18,24,32,108,190,4002" Now say I want to check if the number "8" is in that string. If I use the following, it will return true because 8 is in "18", but I'd want it to return false since the individual number 8 is not there. $search=strpos($numbers,; //returns true What is the best way to get around this? Break the string into an array first then use in_array, or something else? Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/ Share on other sites More sharing options...
Jessica Posted September 19, 2012 Share Posted September 19, 2012 Yes, explode into an array and use in_array. The other more complicated option is to check if 8, is first, ,8 is last, or ,8, exists. The first way is easier and smarter. Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/#findComment-1379418 Share on other sites More sharing options...
Christian F. Posted September 19, 2012 Share Posted September 19, 2012 The use explode () and in_array () is one solution, the other requires Regular Expressions. I recommend the former. Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/#findComment-1379419 Share on other sites More sharing options...
galvin Posted September 19, 2012 Author Share Posted September 19, 2012 Thanks guys, I'll use explode and in_array Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/#findComment-1379421 Share on other sites More sharing options...
kicken Posted September 19, 2012 Share Posted September 19, 2012 The other more complicated option is to check if 8, is first, ,8 is last, or ,8, exists. The first way is easier and smarter. You could just do: $search = str_pos(",{$numbers},", ',8,'); I'd probably go with the explode/in_array solution though, it's a bit more proper. Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/#findComment-1379427 Share on other sites More sharing options...
Jessica Posted September 19, 2012 Share Posted September 19, 2012 The other more complicated option is to check if 8, is first, ,8 is last, or ,8, exists. The first way is easier and smarter. You could just do: $search = str_pos(",{$numbers},", ',8,'); I'd probably go with the explode/in_array solution though, it's a bit more proper. Touche! Quote Link to comment https://forums.phpfreaks.com/topic/268575-strpos-and-numbers/#findComment-1379429 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.