php - PHP 中的 Bash 大括号扩展?

标签 php bash

是否有一种 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/

相关文章:

php - Symfony2 - 如何验证自动完成实体表单类型?

linux - 删除shell中一行的最后一个字

c++ - bash:无法执行二进制文件:Exec 格式错误,即使二进制文件和 Linux 是 64 位的

php - 无法在 Laravel 中迁移文件

php - 未捕获的 PDOException 泄露用户名和密码

php 正则表达式(过滤器?)不应使用正则表达式的地方

bash - SED 命令在 Vagrant Init 脚本中不起作用

php - 无法在实体 A 到 B 之间添加新的 ManyToMany 属性,因为我已经拥有这两个实体的 ManyToMany 属性

bash - ImageMagick 与变量比较的捕获结果

bash - 如何设置 bash 以在按一次 Tab 键时显示自动完成选项?