替换字符串中的占位符以使用替换字符串的所有组合创建字符串数组
对于我正在从事的项目,我有一个带有占位符的基本 URI,并且我想使用 PHP 从每个占位符的可能值数组中生成所有可能的组合。
更具体地说:
$uri = "foo/bar?foo=%foo%&bar=%bar%";
$placeholders = array(
'%foo%' => array('a', 'b'),
'%bar%' => array('c', 'd'),
// ...
);
我希望最终得到以下数组:
array(4) {
[0]=>
string(23) "foo/bar?foo=a&bar=c"
[1]=>
string(23) "foo/bar?foo=a&bar=d"
[2]=>
string(19) "foo/bar?foo=b&bar=c"
[3]=>
string(19) "foo/bar?foo=b&bar=d"
}
当然,更不用说我应该能够添加更多占位符来生成更多计算的 URI,因此该解决方案应该递归地工作。
这些天我可能太累了,但我一直坚持简单地实现这一目标,而且我确信有一个简单的方法,甚至可以使用内置的 PHP 函数......
For a project I'm working on, I have a base URI with placeholders and I want to generate all the possible combinations from an array of possible values for each placeholder using PHP.
More concretely:
$uri = "foo/bar?foo=%foo%&bar=%bar%";
$placeholders = array(
'%foo%' => array('a', 'b'),
'%bar%' => array('c', 'd'),
// ...
);
I'd like ending up having the following array:
array(4) {
[0]=>
string(23) "foo/bar?foo=a&bar=c"
[1]=>
string(23) "foo/bar?foo=a&bar=d"
[2]=>
string(19) "foo/bar?foo=b&bar=c"
[3]=>
string(19) "foo/bar?foo=b&bar=d"
}
Not to mention I should be able to add more placeholders to generate more computed URIs, of course, so the solution should work recursively.
I might be overtired these days, but I'm getting stuck at achieving this simply, and I'm sure there's a simple way, perhaps even with built-in PHP functions…
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是可行的,但它不是那么优雅,因为需要摆脱占位符数组键:
This work, but it's not so elegant because of the need to get rid of the placeholder array keys :
这里的想法是在一个数组中列出所有可能的替换组合。函数 ExpandCombinations 只是在组合中为每个新模式添加一层深度,以无需递归进行替换(我们知道 PHP 多么喜欢递归)。这应该允许替换相当数量的模式,而不会以疯狂的深度递归。
The idea here is to list in an array all the possible combinations for the replacements. The function expandCombinations just adds one level of depth in the combinations for each new pattern to replace with no recursion (we know how PHP loves recursion). This should allow for a decent number of patterns to replace without recursing at an insane depth.
它可以处理无限数量的占位符和占位符。值的数量不受限制
It handles unlimited count of placeholders & unlimited count of values
一种递归解决方案:
每次调用该函数都会从数组中弹出一个占位符,并循环遍历其潜在值,枚举每个占位符的所有剩余占位符值。复杂度为 O(k^n),其中 k 是每个占位符的平均替换次数,n 是占位符的数量。
我的 PHP 有点生疏了;如果我有任何语法错误,请告诉我。
A recursive solution:
Each call to the function pops one placeholder off the array and loops through its potential values enumerating through all the remaining placeholder values for each one. The complexity is O(k^n) where k is the average number of replacements for each placeholder and n is the number of placeholders.
My PHP is a little rusty; let me know if I got any of the syntax wrong.