Ambrosius Topor

Notiz — 2018-12-29

Using 'strtr'

Occasional I prefer using strtr over sprintf to make parameters in a string more clear:

Version using 'sprintf'

$message = sprintf("Failed to parse JSON file '%s': %s (%s)", [
    $filename,
    json_last_error_msg(),
    json_last_error(),
]);

Version using 'strtr'

$message = strtr("Failed to parse JSON file '&filename': &json_error_message (&json_error_code)", [
    '&filename' => $filename,
    '&json_error_message' => json_last_error_msg(),
    '&json_error_code' => json_last_error(),
]);

Of course, it is still possible to use both functions:

$message = strtr("Failed to parse JSON file &filename: &json_error_message (&json_error_code)", [
    '&filename' => sprintf("'%s'", $filename),
    '&json_error_message' => json_last_error_msg(),
    '&json_error_code' => json_last_error(),
]);

We might even implement our own function to handle format strings like this:

$message = /* hypothetical */ sprinttr("Failed to parse JSON file '&{filename%s}': &json_error_message (&json_error_code)", [
    '&filename' => $filename,
    '&json_error_message' => json_last_error_msg(),
    '&json_error_code' => json_last_error(),
]);

Comments

There are no comments yet.

Thanks for your contribution!
Your comment will be visible once it has been approved.

An error occured—please try again.

Add Comment