2009-08-06 93 views
40

我正在构建一个相当大的Lucene.NET搜索表达式。是否有最佳做法的方式来在PHP中进行字符串替换?它不一定是这样,但我希望有类似于C#String.Format方法的东西。C#String.Format()等效于PHP?

下面是C#中逻辑的外观。

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

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

是否有PHP5等价物?

+0

我认为你的字符串占位符的索引必须在crementing,否则会抛出错误。 var filter =“content:{0} title:{1}^4.0 path.title:{2}^4.0 description:{3} ...”; – 2009-08-06 20:48:15

+0

@BeowulfOF如果我的记忆对我很好,不会抛出错误,只需用“Cheese”(在示例中)替换“{0}”的每个实例即可。 – 2013-10-27 12:10:17

回答

65

您可以使用sprintf function

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

或者你自己写函数由相应的参数来代替{i}

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; 
} 
+3

+1你快了10秒! – 2009-08-06 20:26:58

+0

谢谢,Gumbo。 Sprintf做到了这一点,虽然它似乎是基于1而不是基于0的。换句话说,%0 $ s不起作用,但%1 $ s却起作用。再次感谢。 – 2009-08-06 20:43:03

+1

+1链接+样本代码。 – 2009-08-06 20:49:03