Working with strings, numbers, and regular expressions in PHP is relatively easy given the vast number of functions the language provides.
There are times, though, where figuring out how to split on certain criteria may not be immediately clear, or it may be clear what you need to do but not how to best do it.
For example, let’s say that you have a string that’s mixed with both numbers and digits. For this post, let’s say that a given string:
- includes hours and minutes,
- when the minutes are at 60,
- the string should increase the value of the of the hours by one
- the value of the minutes is reset to zero.
An example, problematic string, then, may be of the form T3H60M. How then might we split the string into strings and integers and properly rebuild it?
Split Strings and Integers in PHP
In this instance, there are three things that I’ve found useful. In no particular order:
And the order in which the operations of using each of the above goes something like this:
- use a regular expression to find all of the digits in the string,
- remove everything except the digits in the array
- if the second digit is 60, then set it equal to zero
- increase the first index of the array by one
- rebuild the string.
If the above steps were converted into code, this may be what it would look like:
After that, I determine the value of each of the indexes of the array (and remember, they are strings so you’ll have to cast them as integers to proper increase their value.
Finally, I build the string as (and if) needed.
Sure, this is a bit of a niché case, but the solution can be more generalized based on your own needs.