2

I am trying to duplicate my C# string formatting where i can do something like this:

Console.Writeline("My name is [0].  I have been a [1] for [2] days.", "bob", "member", "12")

I want to be able to do this in PHP, but as far as I know the only function that resembles this is sprintf(). Is there a function that is identical to the one above

echo function("My name is [0].  I have been a [1] for [2] days.", "bob", "member", "12")
10
  • 3
    What's wrong with sprintf()? It is more or less identical to C#'s string formatting. Commented Aug 22, 2011 at 0:23
  • The c# version is type-agnostic; you don't have to specify anything about datatypes or numbers vs. strings if you don't want to. In the simplest form all you need to identify is where in the format string to put specific data items. Commented Aug 22, 2011 at 0:31
  • 2
    @Joe If you simply specify everything as %s, sprintf is basically type-agnositc as well. You don't have to use any of the other types. Commented Aug 22, 2011 at 3:45
  • 3
    @Volker sprintf allows that as well, only the syntax is not as nice: %1$s. Commented Aug 22, 2011 at 7:31
  • 1
    @deceze 5 examples for argument swapping on the manual page and I never noticed that. thanks. Commented Aug 22, 2011 at 8:04

2 Answers 2

6

You could write your own function like e.g.

<?php
function Format($format /*, ... */) {
    $args = func_get_args();
    return preg_replace_callback('/\[(\\d)\]/',
        function($m) use($args) {
            // might want to add more error handling here...
            return $args[$m[1]+1];
        },
        $format
    );
}

$x = 'a';
$y = 'b';
echo Format('1=[1], 0=[0]', $x, $y);
Sign up to request clarification or add additional context in comments.

Comments

1

You could inline variables in the string:

$frob = "John";
$foo = "Hello $frob!";

1 Comment

This does not work for me. I would have surprised me, if it did.

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.