Skip to content
Advertisement

PHP REGEX: how to pad numbers in the middle/end of a string

i have a list of key=>value pairs from a JSON squirt. i sorted the array and i’m left with the following (excerpted relevant cases because they go as high as 92):

JavaScript

what i need to do is: 1) place all the digits at the end and 2) pad them to 2 digits (01,02,&c) so the list ends up looking like this:

JavaScript

i was hoping to do this with one REGEX statement given the obvious similarity in key names, but i got lost. here’s what i have so far:

JavaScript

…aaaand i’m lost what to do next. how to move on? is there a better compact way to do this?

EDIT: this also means i have to replace ‘dir’ with ‘directive’. it’s implied in the result list, but i didnt’ make a bullet item for it. also, the REGEX is all i was able to build at RegExer. thus the “lost what to do next” part.

Advertisement

Answer

  • Match but don’t capture dir
  • Match but don’t capture the optional substring ective
  • Retain zero or more non-digital characters immediately after ective as capture group #1 (this accounts for optional substrings like summarydue)
  • Retain the whole integer as capture group #2
  • Retain the remainder of the string as capture group #3

  • In the custom function, hardcode directive, then append capture group #1 (which may be empty), then capture group #3 (might also be empty), finally left pad capture group #2 with a zero to a maximum length of 2-digits and append that value to the end of the string

Code: (Demo)

JavaScript

Output:

JavaScript

Alternatively, you could parse the string with sscanf(), then print the isolated components in the desired format with printf().

Code: (Demo)

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement