galvin Posted November 19, 2014 Share Posted November 19, 2014 Say you have a string that you know has two, and exactly two, periods in it, like this... $string = "3.12.8" How can you grab the three different values that are separated by periods (in this case, 3, 12 and ? I was thinking use strpos to find the position of the first period, then could use that info to grab everything up to that position. But then I couldn't figure out how you would find the position of the SECOND period. And even if I could get the exact positions of the two periods, it seems like there should be an easier way to simply retrieve values separated by specific characters. Is there a specific function for this type of thing, or was my initial though correct with having to do it in two parts essentially (find positions of periods, then use that knowledge to get the values)? Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/292562-parse-out-values-in-string-separated-by-periods/ Share on other sites More sharing options...
bsmither Posted November 19, 2014 Share Posted November 19, 2014 (edited) By using the command explode(), you will be given an array containing everything that is separated by the 'glue' character(s). Your statement would be: $arResult = explode('.', $string); The $arResult array will be: Array( [0] => '3' [1] => '12' [2] => '8' ) Be aware however, that a string such as: "3.12.8.234.5.12.89.49.34" will have nine elements in the array. If you wish to deal with only the first three (being separated by the first two periods), then $arResult[0], [1], and [2] will be your working variables. If you want to keep the third element undisturbed, that is, $arResult[2] just happens to end up being "8.234.5.12.89.49.34", then there will be some more processing by concatenating elements 2-8 back into a string. Edited November 19, 2014 by bsmither Quote Link to comment https://forums.phpfreaks.com/topic/292562-parse-out-values-in-string-separated-by-periods/#findComment-1496977 Share on other sites More sharing options...
requinix Posted November 19, 2014 Share Posted November 19, 2014 If you want to keep the third element undisturbed, that is, $arResult[2] just happens to end up being "8.234.5.12.89.49.34", then there will be some more processing by concatenating elements 2-8 back into a string.explode()s third argument lets you limit the number of items to, say, 3, with the third having the rest of the string. Quote Link to comment https://forums.phpfreaks.com/topic/292562-parse-out-values-in-string-separated-by-periods/#findComment-1496979 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.