是否有一种 php 方法可以完成 bash 大括号扩展?例如
[chiliNUT@server ~]$ echo {hello,hi,hey}\ {friends,world},
hello friends, hello world, hi friends, hi world, hey friends, hey world,
有点像
<?php
echo brace_expand("{hello,hi,hey} {friends,world}");
//hello friends, hello world, hi friends, hi world, hey friends, hey world,
目前我正在使用
<?php
echo shell_exec("echo {hello,hi,hey}\ {friends,world}");
但这似乎不是正确的方法(并且可能不适用于 Windows 服务器)
注意这仅适用于打印字符串的用例,不适用于大括号扩展的任何其他功能,例如与运行命令组相关的功能。
最佳答案
这应该适合您的情况(您可以改进它):
<?php
function brace_expand($string)
{
preg_match_all("/\{(.*?)(\})/", $string, $Matches);
if (!isset($Matches[1]) || !isset($Matches[1][0]) || !isset($Matches[1][1])) {
return false;
}
$LeftSide = explode(',', $Matches[1][0]);
$RightSide = explode(',', $Matches[1][1]);
foreach ($LeftSide as $Left) {
foreach ($RightSide as $Right) {
printf("%s %s" . PHP_EOL, $Left, $Right);
}
}
}
brace_expand("{hello,hi,hey} {friends,world}");
输出:
hello friends
hello world
hi friends
hi world
hey friends
hey world
编辑:无限大括号支持
<?php
function brace_expand($string)
{
preg_match_all("/\{(.*?)(\})/", $string, $Matches);
$Arrays = [];
foreach ($Matches[1] as $Match) {
$Arrays[] = explode(',', $Match);
}
return product($Arrays);
}
function product($a)
{
$result = array(array());
foreach ($a as $list) {
$_tmp = array();
foreach ($result as $result_item) {
foreach ($list as $list_item) {
$_tmp[] = array_merge($result_item, array($list_item));
}
}
$result = $_tmp;
}
return $result;
}
print_r(brace_expand("{hello,hi,hey} {friends,world} {me, you, we} {lorem, ipsum, dorem}"));
关于php - PHP 中的 Bash 大括号扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39454728/