Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# String.Format() Equivalent in PHP?

Tags:

c#

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?

like image 538
Ben Griswold Avatar asked Aug 06 '09 20:08

Ben Griswold


1 Answers

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; } 
like image 180
Gumbo Avatar answered Oct 13 '22 13:10

Gumbo