1

I am displaying address data that is pulled from customer-supplied records, and trying to format it properly. Each client can specify how they want their customer data to appear, so I am using an editable JSON-based template for each client that makes use of php's sprintf() and it's formatting capability.

So client A, wanting their addresses to appear like:

Bill Smith
123 Fake St
Whoville, OH

Would have a saved format of %s<br>%s<br>%s, %s.

Client B wants:

Bill Smith
123 Fake St, Whoville, OH 94301

With a saved format of %s<br>%s, %s, %s %s

I then store these formattings in a client-specific template that tells me which fields to pull from and the format, i.e:

{
    "fields": [
        "full_name",
        "street",
        "city",
        "state",
        "zip"
    ],
    "format": "%s<br>%s, %s, %s %s"
}

Decoding the JSON, pulling the data and writing it using sprintf() with the supplied format works well, and doesn't require me creating a custom formatting function to handle the various address formats. The problem is that if a piece of data is empty, it gets displayed, i.e. if the street address is missing, we have:

Bill Smith
, Whoville, OH 94301

I am trying to come up with a solution that doesn't require re-inventing the wheel, but am open to other architectures that will give me the flexibility to handle 'optional' data with corresponding flexible formatting.

1 Answer 1

1

I've found and implemented a solution that works rather well, based on this answer.

Essentially, I am breaking up the formatting components and matching them with the data components, so that I have something like:

{
  "data": "Bill Smith",
  "format": "%s"
},
{
  "data": "123 Fake St",
  "format": "<br>%s,"
},
{
  "data": "Whoville",
  "format": " %s,"
},
{
  "data": "OH",
  "format": " %s"
}

When I run through the above components, I then check for a value in .data and if found, concatenate the format component to a format variable. At the end, I run the data components and the concatenated format string through vsprintf(). Not perfect, but working better than before and fairly flexible.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.