php中的Pythonlike.format()

2024-04-20 07:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下数组:

$matches[0] = "123";
$matches[1] = "987";
$matches[2] = "121";

以及以下字符串:

$result = "My phone number is {0} and police number is {2}";

我想替换基于$matches数组的{}占位符,以防占位符不匹配而显示nothing。你知道吗

实现这一目标的最佳方法是什么?或者你知道解决我问题的更好方法吗?你知道吗

(现在我正在构建这个系统,因此我可以使用任何其他符号,而不是花括号)

更新

在python中,这可以使用.format()函数实现。你知道吗


Tags: and方法字符串number目标ismy系统
1条回答
网友
1楼 · 发布于 2024-04-20 07:41:43

你可以用vsprintf来做,如果你给你的项目的数字(从1开始)如下:%n$s(其中n是数字):

$matches = [ "123", "987", "121"];
$result = 'My phone number is %1$s and police number is %3$s';

$res = vsprintf($result, $matches);

请注意,您必须将格式化的字符串放在单引号之间,否则$s将被解释为变量并被替换为零。你知道吗

vprintfvsprintf是为数组设计的,但是你可以用printfsprintf做同样的事情,对于分离的变量,它的工作原理是一样的)


如果无法更改原始的Python格式的字符串,方法是使用preg_replace_callback

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$res = preg_replace_callback('~{(\d+)}~', function ($m) use ($matches) {
    return isset($matches[$m[1]]) ? $matches[$m[1]] : $m[0];
}, $result);

或者,您可以构建一个关联数组,其中键是占位符和数组值,并使用strtr替换:

$matches = [ "123", "987", "121"];
$result = 'My phone number is {0} and police number is {2}';

$trans = array_combine(
    array_map(function ($i) { return '{'.$i.'}'; }, array_keys($matches)),
    $matches
);

$result = strtr($result, $trans);

相关问题 更多 >