C# String.Format() 在 PHP 中等效吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1241177/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:05:31  来源:igfitidea点击:

C# String.Format() Equivalent in PHP?

c#php

提问by Ben Griswold

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.

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

Here's what the logic would look like in C#.

下面是 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?

有PHP5等价物吗?

采纳答案by Gumbo

You could use the sprintffunction:

您可以使用该sprintf功能

$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:

或者您编写自己的函数来替换相应的参数:{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;
}

回答by Mateusz Kubiczek

回答by Irfan Soetedja

try this one if there is an error or 'create_function'

如果出现错误或“create_function”,请尝试此操作

public static function format()
{
    $args = func_get_args();
    $format = array_shift($args);

    preg_match_all('/(?=\{)\{(\d+)\}(?!\})/', $format, $matches, PREG_OFFSET_CAPTURE);
    $offset = 0;
    foreach ($matches[1] as $data) {
        $i = $data[0];
        $format = substr_replace($format, @$args[$i], $offset + $data[1] - 1, 2 + strlen($i));
        $offset += strlen(@$args[$i]) - 2 - strlen($i);
    }

    return $format;
}

I found it from here

我从这里找到的