Jump to content

Parse out values in string separated by periods


galvin

Recommended Posts

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 8)?

 

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!

Link to comment
Share on other sites

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 by bsmither
Link to comment
Share on other sites

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.
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.