2

我有一个用于构建字符串的预定义模式,应该在整个脚本中定期创建。

$str="$first - $second @@ $third"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";
$string= ..?? // string should be built here based on the pattern

目前,我正在使用eval基于最初定义的模式生成适当的字符串。但是,由于这种情况偶尔会发生并且eval通常很糟糕,我希望找到另一种方法。

请注意,模式在所有代码之上只定义一次,我只能通过一行来编辑所有脚本的模式。因此,任何$string改变都不应触及

我试过create_function了,但需要相同数量的参数。使用eval,我可以轻松更改模式,但是使用create-function,我需要更改整个脚本。例如,如果将字符串模式更改为

$str="$first @@ $second"; // One arg/var is dropped

评估示例:

$str="$first - $second @@ $third"; // Pattern is defined one-time before codes
$first="word1";
$second="word2";
$third="word3";
eval("\$string = \"$str\";");

create_function 示例:

$str=create_function('$first,$second,$third', 'return "$first - $second @@ $third";');
$string=$str($first,$second,$third);
4

3 回答 3

3

您可以使用sprintf或提供的字符串格式化功能vsprintf

$format = "%s - %s @@ %s"; // pattern for building the string
$first = "word1";
$second = "word2";
$third = "word3";
$string = sprintf($format, $first, $second, $third);

vsprintf如果你想传递一个数组,你可以使用。

$format = "%s - %s @@ %s"; // pattern for building the string
$values = array($first, $second, $third);
$string = vsprintf($format, $values);
于 2012-11-06T06:00:08.737 回答
0

这可能会有所帮助,不确定。

$str = "_first_ - _second_ @@ _third_"; // pattern for building the string
// _first, _second_... are placeholders for actual values

// this function performs the string building
function buildString( $arr ) {
   global $str;

   $keys = array_keys( $arr );
   $vals = array_values( $arr );

   return eval( str_replace( $keys, $vals, $str ) );
}

while(some condition here) {
    $str = 'A new string'; // you can change your string builiding pattern here

    // this array is built in the fashion ->
    // keys of array are the variables in $str and
    // their actual values are the values of $str
    $arr=array('_first_' => $first, '_second_' => $second, '_third_' => $third);
    echo buildString( $arr );
}
于 2012-11-06T05:47:18.633 回答
0

对我来说似乎是相当简单的事情。str_replace()基于模式的使用和替换

$str="$first$ - $second$ @@ $third$"; // pattern for building the string
$first="word1";
$second="word2";
$third="word3";

$newstr = str_replace('$first$', $first, $str);
$newstr = str_replace('$second$', $second, $newstr);
$newstr = str_replace('$third$', $third, $newstr);
于 2012-11-06T05:41:23.207 回答