![](/img/trans.png)
[英]Does PHP have a string function like Python's f-string function? (not str.format())
[英]Python-like .format() in php
我有以下数组:
$matches[0] = "123";
$matches[1] = "987";
$matches[2] = "121";
以下字符串:
$result = "My phone number is {0} and police number is {2}";
我想基于$matches
数组替换{}
占位符,以防占位符显示没有匹配。
实现这一目标的最佳方法是什么,或者您是否知道更好的解决方案?
(现在我正在构建系统,所以我可以使用任何其他符号而不是花括号)
在python中,这可以使用.format()
函数。
您可以使用vsprintf
执行此操作,如果您给出项目的数字(从1 vsprintf
,则不必更改项目的顺序: %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
将被解释为变量并替换为空。
( vprintf
和vsprintf
是为数组设计的,但是对于分离的变量,你可以用printf
和sprintf
做同样的事情,它的工作方式相同)
如果您无法更改原始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
,并使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.