tags:

views:

656

answers:

2

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?

+7  A: 

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;
}
Gumbo
+1 You were 10 seconds faster!
Andrew Hare
Thanks, Gumbo. Sprintf did the trick, although it seems to be 1-based rather than 0-based. In other words, %0$s didn't work but %1$s does. Thanks again.
Ben Griswold
+1 for link + samplecode.
BeowulfOF
+2  A: 

Try sprintf http://php.net/sprintf

Mateusz Kubiczek