Skip to content
Advertisement

C# String.Format() Equivalent in PHP?

I’m building a rather large Lucene.NET search expression. Is there a best practices way to do the string replacement in PHP? It doesn’t have to be this way, but I’m hoping for something similar to the C# String.Format method.

Here’s what the logic would look like in C#.

var filter = "content:{0} title:{0}^4.0 path.title:{0}^4.0 description:{0} ...";

filter = String.Format(filter, "Cheese");

Is there a PHP5 equivalent?

Advertisement

Answer

You could use the sprintf function:

$filter = "content:%1$s title:%1$s^4.0 path.title:%1$s^4.0 description:%1$s ...";
$filter = sprintf($filter, "Cheese");

Or you write your own function to replace the {i} by the corresponding argument:

function format() {
    $args = func_get_args();
    if (count($args) == 0) {
        return;
    }
    if (count($args) == 1) {
        return $args[0];
    }
    $str = array_shift($args);
    $str = preg_replace_callback('/\{(0|[1-9]\d*)\}/', create_function('$match', '$args = '.var_export($args, true).'; return isset($args[$match[1]]) ? $args[$match[1]] : $match[0];'), $str);
    return $str;
}
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement