Split Strings and Integers in PHP Using Regular Expressions Using preg_split and a few native PHP functions to easily separate integers and strings in PHP.

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.

Split Strings and Integers in PHP Using Regular Expressions
Photo by Agê Barros on Unsplash

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:

  1. use a regular expression to find all of the digits in the string,
  2. remove everything except the digits in the array
  3. if the second digit is 60, then set it equal to zero
  4. increase the first index of the array by one
  5. rebuild the string.

If the above steps were converted into code, this may be what it would look like:

Note that I opt to use array_filter to remove duplicate values and use array_values to clean the array up into just two entries the first of which is the hour, the second of which is the minute.

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.