带有命名参数的 vsprintf 或 sprintf,或者 PHP 中的简单模板解析

发布于 2024-11-02 07:58:08 字数 794 浏览 6 评论 0原文

我正在寻找一种为 sprintfprintf 使用命名参数的方法。

示例:

sprintf(
  'Last time logged in was %hours hours, 
   %minutes minutes, %seconds seconds ago'
  ,$hours,$minutes, $seconds
);

或通过 vsprintf 和关联数组。

我在这里找到了一些编码示例

function sprintfn ($format, array $args = array())

http://php.net/manual/de/function .sprintf.php

和这里

function vnsprintf( $format, array $data)

http://php.net/manual/de/function.vsprintf.php

人们编写了自己的解决方案。

有没有内置的 PHP 函数可以实现这一点?

I'm searching for a way to use named arguments for sprintf or printf.

Example:

sprintf(
  'Last time logged in was %hours hours, 
   %minutes minutes, %seconds seconds ago'
  ,$hours,$minutes, $seconds
);

or via vsprintf and an associative array.

I have found some coding examples here

function sprintfn ($format, array $args = array())

http://php.net/manual/de/function.sprintf.php

and here

function vnsprintf( $format, array $data)

http://php.net/manual/de/function.vsprintf.php

where people wrote their own solutions.

Is there a built-in PHP function to achieve this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

分分钟 2024-11-09 07:58:08

迟到了,但您可以简单地使用 strtr 来“翻译字符”或替换子字符串”

<?php

$hours = 2;
$minutes = 24;
$seconds = 35;

// Option 1: Replacing %variable
echo strtr(
    'Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago',
    [
        '%hours' => $hours,
        '%minutes' => $minutes,
        '%seconds' => $seconds
    ]
);

// Option 2: Alternative replacing {variable}
echo strtr(
    'Last time logged in was  {hours} hours, {minutes} minutes, {seconds} seconds ago',
    [
        '{hours}' => $hours,
        '{minutes}' => $minutes,
        '{seconds}' => $seconds
    ]
);

// Option 3: Using an array with variables:
$data = [
    '{hours}' => 2,
    '{minutes}' => 24,
    '{seconds}' => 35,
];

echo strtr('Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago', $data);

// More options: Of course you can replace any string....

输出以下内容:

上次登录时间是 2 小时 24 分 35 秒前

Late to the party, but you can simply use strtr to "translate characters or replace substrings"

<?php

$hours = 2;
$minutes = 24;
$seconds = 35;

// Option 1: Replacing %variable
echo strtr(
    'Last time logged in was %hours hours, %minutes minutes, %seconds seconds ago',
    [
        '%hours' => $hours,
        '%minutes' => $minutes,
        '%seconds' => $seconds
    ]
);

// Option 2: Alternative replacing {variable}
echo strtr(
    'Last time logged in was  {hours} hours, {minutes} minutes, {seconds} seconds ago',
    [
        '{hours}' => $hours,
        '{minutes}' => $minutes,
        '{seconds}' => $seconds
    ]
);

// Option 3: Using an array with variables:
$data = [
    '{hours}' => 2,
    '{minutes}' => 24,
    '{seconds}' => 35,
];

echo strtr('Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago', $data);

// More options: Of course you can replace any string....

outputs the following:

Last time logged in was 2 hours, 24 minutes, 35 seconds ago

粉红×色少女 2024-11-09 07:58:08

我专门为这个需要编写了一个小组件。它称为 StringTemplate
有了它,您可以通过如下代码获得您想要的东西:

$engine = new StringTemplate\Engine;

$engine->render(
   'Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago',
   [
      'hours' => '08',
      'minutes' => 23,
      'seconds' => 12,
   ]
);
//Prints "Last time logged in was 08 hours, 23 minutes, 12 seconds ago"

希望能有所帮助。

I've written a small component exactly for this need. It's called StringTemplate.
With it you can get what you want with a code like this:

$engine = new StringTemplate\Engine;

$engine->render(
   'Last time logged in was {hours} hours, {minutes} minutes, {seconds} seconds ago',
   [
      'hours' => '08',
      'minutes' => 23,
      'seconds' => 12,
   ]
);
//Prints "Last time logged in was 08 hours, 23 minutes, 12 seconds ago"

Hope that can help.

埖埖迣鎅 2024-11-09 07:58:08

据我所知 printf/sprintf 不接受 assoc 数组。

然而,可以做 printf('%1$d %1$d', 1);

总比什么都不做好;)

As far as I know printf/sprintf does not accept assoc arrays.

However it is possible to do printf('%1$d %1$d', 1);

Better than nothing ;)

还给你自由 2024-11-09 07:58:08

这是来自 php.net

function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys, TRUE) ) !== FALSE || ( is_numeric( $value[1][0] ) && ( $key = array_search( (int)$value[1][0], $keys, TRUE) ) !== FALSE) )
        {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( 1 + $key);
        }
    }
    return vsprintf( $format, $data);
}

示例:

$example = array(
    0 => 'first',
    'second' => 'second',
    'third',
    4.2 => 'fourth',
    'fifth',
    -6.7 => 'sixth',
    'seventh',
    'eighth',
    '9' => 'ninth',
    'tenth' => 'tenth',
    '-11.3' => 'eleventh',
    'twelfth'
);

echo vnsprintf( '%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s %10$s %11$s %12$s<br />', $example); // acts like vsprintf
echo vnsprintf( '%+0$s %second$s %+1$s %+4$s %+5$s %-6.5$s %+6$s %+7$s %+9$s %tenth$s %-11.3$s %+10$s<br />', $example);

示例 2:

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"

This is from php.net

function vnsprintf( $format, array $data)
{
    preg_match_all( '/ (?<!%) % ( (?: [[:alpha:]_-][[:alnum:]_-]* | ([-+])? [0-9]+ (?(2) (?:\.[0-9]+)? | \.[0-9]+ ) ) ) \$ [-+]? \'? .? -? [0-9]* (\.[0-9]+)? \w/x', $format, $match, PREG_SET_ORDER | PREG_OFFSET_CAPTURE);
    $offset = 0;
    $keys = array_keys($data);
    foreach( $match as &$value )
    {
        if ( ( $key = array_search( $value[1][0], $keys, TRUE) ) !== FALSE || ( is_numeric( $value[1][0] ) && ( $key = array_search( (int)$value[1][0], $keys, TRUE) ) !== FALSE) )
        {
            $len = strlen( $value[1][0]);
            $format = substr_replace( $format, 1 + $key, $offset + $value[1][1], $len);
            $offset -= $len - strlen( 1 + $key);
        }
    }
    return vsprintf( $format, $data);
}

Example:

$example = array(
    0 => 'first',
    'second' => 'second',
    'third',
    4.2 => 'fourth',
    'fifth',
    -6.7 => 'sixth',
    'seventh',
    'eighth',
    '9' => 'ninth',
    'tenth' => 'tenth',
    '-11.3' => 'eleventh',
    'twelfth'
);

echo vnsprintf( '%1$s %2$s %3$s %4$s %5$s %6$s %7$s %8$s %9$s %10$s %11$s %12$s<br />', $example); // acts like vsprintf
echo vnsprintf( '%+0$s %second$s %+1$s %+4$s %+5$s %-6.5$s %+6$s %+7$s %+9$s %tenth$s %-11.3$s %+10$s<br />', $example);

Example 2:

$examples = array(
    2.8=>'positiveFloat',    // key = 2 , 1st value
    -3=>'negativeInteger',    // key = -3 , 2nd value
    'my_name'=>'someString'    // key = my_name , 3rd value
);

echo vsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // [unsupported]
echo vnsprintf( "%%my_name\$s = '%my_name\$s'\n", $examples);    // output : "someString"

echo vsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%2.5\$s = '%2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2.5\$s = '%+2.5\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3.2\$s = '%-3.2\$s'\n", $examples);        // output : "negativeInteger"

echo vsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : "negativeInteger"
echo vnsprintf( "%%2\$s = '%2\$s'\n", $examples);            // output : [= vsprintf]

echo vsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%+2\$s = '%+2\$s'\n", $examples);        // output : "positiveFloat"

echo vsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // [unsupported]
echo vnsprintf( "%%-3\$s = '%-3\$s'\n", $examples);        // output : "negativeInteger"
心的憧憬 2024-11-09 07:58:08

我知道这个问题已经解决了太久了,但也许我的解决方案足够简单,但对其他人有用。

通过这个小功能,您可以模仿一个简单的模板系统:

function parse_html($html, $args) {

  foreach($args as $key => $val) $html = str_replace("#[$key]", $val, $html);

  return $html;
}

像这样使用它:

$html = '<h1>Hello, #[name]</h1>';
$args = array('name' => 'John Appleseed';

echo parse_html($html,$args);

这将输出:

<h1>Hello, John Appleseed</h1>

也许不适合每个人和每种情况,但它救了我。

I know this has been resolved for too long now, but maybe my solution is simple enough, yet useful for somebody else.

With this little function you can mimic a simple templating system:

function parse_html($html, $args) {

  foreach($args as $key => $val) $html = str_replace("#[$key]", $val, $html);

  return $html;
}

Use it like this:

$html = '<h1>Hello, #[name]</h1>';
$args = array('name' => 'John Appleseed';

echo parse_html($html,$args);

This would output:

<h1>Hello, John Appleseed</h1>

Maybe not for everyone and every case, but it saved me.

紫罗兰の梦幻 2024-11-09 07:58:08

请参阅 drupal 的实现

https://api.drupal.org/ api/drupal/includes%21bootstrap.inc/function/format_string/7

很简单,不使用正则

function format_string($string, array $args = array()) {
  // Transform arguments before inserting them.
  foreach ($args as $key => $value) {
    switch ($key[0]) {
      case '@':
        // Escaped only.
        $args[$key] = check_plain($value);
        break;

      case '%':
      default:
        // Escaped and placeholder.
        $args[$key] = drupal_placeholder($value);
        break;

      case '!':
        // Pass-through.
    }
  }
  return strtr($string, $args);
}

function drupal_placeholder($text) {
  return '<em class="placeholder">' . check_plain($text) . '</em>';
}

表达式示例:

$unformatted = 'Hello, @name';
$formatted = format_string($unformatted, array('@name' => 'John'));

See drupal's implementation

https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/format_string/7

It's simple and doesn't use regexp

function format_string($string, array $args = array()) {
  // Transform arguments before inserting them.
  foreach ($args as $key => $value) {
    switch ($key[0]) {
      case '@':
        // Escaped only.
        $args[$key] = check_plain($value);
        break;

      case '%':
      default:
        // Escaped and placeholder.
        $args[$key] = drupal_placeholder($value);
        break;

      case '!':
        // Pass-through.
    }
  }
  return strtr($string, $args);
}

function drupal_placeholder($text) {
  return '<em class="placeholder">' . check_plain($text) . '</em>';
}

Example:

$unformatted = 'Hello, @name';
$formatted = format_string($unformatted, array('@name' => 'John'));
一百个冬季 2024-11-09 07:58:08

从5.3开始,因为use关键字:

此函数支持格式化{{var}}或{{dict.key}},您可以更改{{} }{} 等以符合您的喜好。

function formatString($str, $data) {
    return preg_replace_callback('#{{(\w+?)(\.(\w+?))?}}#', function($m) use ($data){
        return count($m) === 2 ? $data[$m[1]] : $data[$m[1]][$m[3]];
    }, $str);
}

示例:

$str = "This is {{name}}, I am {{age}} years old, I have a cat called {{pets.cat}}.";
$dict = [
    'name' => 'Jim',
    'age' => 20,
    'pets' => ['cat' => 'huang', 'dog' => 'bai']
];
echo formatString($str, $dict);

输出:

这是吉姆,我今年 20 岁,我有一只猫叫黄。

Since 5.3 because of the use keyword:

This function supports formatting {{var}} or {{dict.key}}, you can change the {{}} to {} etc to match you favor.

function formatString($str, $data) {
    return preg_replace_callback('#{{(\w+?)(\.(\w+?))?}}#', function($m) use ($data){
        return count($m) === 2 ? $data[$m[1]] : $data[$m[1]][$m[3]];
    }, $str);
}

Example:

$str = "This is {{name}}, I am {{age}} years old, I have a cat called {{pets.cat}}.";
$dict = [
    'name' => 'Jim',
    'age' => 20,
    'pets' => ['cat' => 'huang', 'dog' => 'bai']
];
echo formatString($str, $dict);

Output:

This is Jim, I am 20 years old, I have a cat called huang.

疏忽 2024-11-09 07:58:08

这就是我正在使用的:

$arr = ['a' => 'happy','b' => 'funny'];

$templ = "I m a [a] and [b] person";

$r = array_walk($arr,function($i,$k) use(&$templ){
    $templ = str_replace("[$k]",$i,$templ);
} );

var_dump($templ);

This is what I'm using:

$arr = ['a' => 'happy','b' => 'funny'];

$templ = "I m a [a] and [b] person";

$r = array_walk($arr,function($i,$k) use(&$templ){
    $templ = str_replace("[$k]",$i,$templ);
} );

var_dump($templ);
时间你老了 2024-11-09 07:58:08

恕我直言,这确实是最好的方式。没有神秘字符,只需使用键名即可!

取自 php 站点:
http://www.php.net/manual/en /function.vsprintf.php

function dsprintf() {
  $data = func_get_args(); // get all the arguments
  $string = array_shift($data); // the string is the first one
  if (is_array(func_get_arg(1))) { // if the second one is an array, use that
    $data = func_get_arg(1);
  }
  $used_keys = array();
  // get the matches, and feed them to our function
  $string = preg_replace('/\%\((.*?)\)(.)/e',
    'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string);
  $data = array_diff_key($data,$used_keys); // diff the data with the used_keys
  return vsprintf($string,$data); // yeah!
}

function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
  if (isset($data[$m1])) { // if the key is there
    $str = $data[$m1];
    $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
    return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
  } else {
    return "%".$m2; // else, return a regular %s, or %d or whatever is used
  }
}

$str = <<<HITHERE
Hello, %(firstName)s, I know your favorite PDA is the %(pda)s. You must have bought %(amount)s
HITHERE;

$dataArray = array(
  'pda'         => 'Newton 2100',
  'firstName'   => 'Steve',
  'amount'      => '200'
);
echo dsprintf($str, $dataArray);
// Hello, Steve, I know your favorite PDA is the Newton 2100. You must have bought 200

This is really the best way to go imho. No cryptic characters, just use the key names!

As taken from the php site:
http://www.php.net/manual/en/function.vsprintf.php

function dsprintf() {
  $data = func_get_args(); // get all the arguments
  $string = array_shift($data); // the string is the first one
  if (is_array(func_get_arg(1))) { // if the second one is an array, use that
    $data = func_get_arg(1);
  }
  $used_keys = array();
  // get the matches, and feed them to our function
  $string = preg_replace('/\%\((.*?)\)(.)/e',
    'dsprintfMatch(\'$1\',\'$2\',\$data,$used_keys)',$string);
  $data = array_diff_key($data,$used_keys); // diff the data with the used_keys
  return vsprintf($string,$data); // yeah!
}

function dsprintfMatch($m1,$m2,&$data,&$used_keys) {
  if (isset($data[$m1])) { // if the key is there
    $str = $data[$m1];
    $used_keys[$m1] = $m1; // dont unset it, it can be used multiple times
    return sprintf("%".$m2,$str); // sprintf the string, so %s, or %d works like it should
  } else {
    return "%".$m2; // else, return a regular %s, or %d or whatever is used
  }
}

$str = <<<HITHERE
Hello, %(firstName)s, I know your favorite PDA is the %(pda)s. You must have bought %(amount)s
HITHERE;

$dataArray = array(
  'pda'         => 'Newton 2100',
  'firstName'   => 'Steve',
  'amount'      => '200'
);
echo dsprintf($str, $dataArray);
// Hello, Steve, I know your favorite PDA is the Newton 2100. You must have bought 200
dawn曙光 2024-11-09 07:58:08

您需要避免在自定义函数中使用 %,因为它可能会干扰其他实现,例如 SQL 中的日期格式,所以...

function replace(string $string, iterable $replacements): string
{
    return str_replace(
        array_map(
            function($k) {
                return sprintf("{%s}", $k);
            },
            array_keys($replacements)
        ),
        array_values($replacements),
        $string
    );      
}

$string1 = 'Mary had a little {0}. Its {1} was white as {2}.';

echo replace($string1, ['lamb', 'fleece', 'snow']);

$string2 = 'Mary had a little {animal}. Its {coat} was white as {color}.';

echo replace($string2, ['animal' => 'lamb', 'coat' => 'fleece', 'color' => 'snow']);

$string1: Mary 有一只小羊羔。它的羊毛洁白如雪。
$string2:玛丽有一只小羊羔。它的羊毛洁白如雪。

You'll want to avoid using % in you custom functions as it can interfere with other implementations, for example, date formatting in SQL, so...

function replace(string $string, iterable $replacements): string
{
    return str_replace(
        array_map(
            function($k) {
                return sprintf("{%s}", $k);
            },
            array_keys($replacements)
        ),
        array_values($replacements),
        $string
    );      
}

$string1 = 'Mary had a little {0}. Its {1} was white as {2}.';

echo replace($string1, ['lamb', 'fleece', 'snow']);

$string2 = 'Mary had a little {animal}. Its {coat} was white as {color}.';

echo replace($string2, ['animal' => 'lamb', 'coat' => 'fleece', 'color' => 'snow']);

$string1: Mary had a little lamb. Its fleece was white as snow.
$string2: Mary had a little lamb. Its fleece was white as snow.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文