php – 正则表达式匹配无限数量的选项

前端之家收集整理的这篇文章主要介绍了php – 正则表达式匹配无限数量的选项前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望能够像这样解析文件路径:
/var/www/index.(htm|html|PHP|shtml)

进入有序数组:

array("htm","html","PHP","shtml")

然后生成一个备选列表:

/var/www/index.htm
/var/www/index.html
/var/www/index.PHP
/var/www/index.shtml

现在,我有一个preg_match语句可以拆分两个选项:

preg_match_all ("/\(([^)]*)\|([^)]*)\)/",$path_resource,$matches);

有人可以给我一个指针,如何扩展它以接受无限数量的替代品(至少两个)?关于正则表达式,其余的我可以处理.

规则是:

>列表需要以a开头(并以a结尾)
>必须有一个|在清单中(即至少两个备选方案)
>(或)的任何其他事件将保持不变.

更新:我需要能够处理多个括号对,例如:

/var/(www|www2)/index.(htm|html|PHP|shtml)

对不起,我没有马上说出来.

Update 2: If you’re looking to do what I’m trying to do in the filesystem,then note that glob() already brings this functionality out of the Box. There is no need to implement a custom solutiom. See @Gordon’s answer below for details.

非正则表达式解决方案:)
<?PHP

$test = '/var/www/index.(htm|html|PHP|shtml)';

/**
 *
 * @param string $str "/var/www/index.(htm|html|PHP|shtml)"
 * @return array "/var/www/index.htm","/var/www/index.PHP",etc
 */
function expand_bracket_pair($str)
{
    // Only get the very last "(" and ignore all others.
    $bracketStartPos = strrpos($str,'(');
    $bracketEndPos = strrpos($str,')');

    // Split on ",".
    $exts = substr($str,$bracketStartPos,$bracketEndPos - $bracketStartPos);
    $exts = trim($exts,'()|');
    $exts = explode('|',$exts);

    // List all possible file names.
    $names = array();

    $prefix = substr($str,$bracketStartPos);
    $affix = substr($str,$bracketEndPos + 1);
    foreach ($exts as $ext)
    {
        $names[] = "{$prefix}{$ext}{$affix}";
    }

    return $names;
}

function expand_filenames($input)
{
    $nbBrackets = substr_count($input,'(');

    // Start with the last pair.
    $sets = expand_bracket_pair($input);

    // Now work backwards and recurse for each generated filename set.
    for ($i = 0; $i < $nbBrackets; $i++)
    {
        foreach ($sets as $k => $set)
        {
            $sets = array_merge(
                $sets,expand_bracket_pair($set)
            );
        }
    }

    // Clean up.
    foreach ($sets as $k => $set)
    {
        if (false !== strpos($set,'('))
        {
            unset($sets[$k]);
        }
    }
    $sets = array_unique($sets);
    sort($sets);

    return $sets;
}

var_dump(expand_filenames('/(a|b)/var/(www|www2)/index.(htm|html|PHP|shtml)'));
原文链接:https://www.f2er.com/php/132891.html

猜你在找的PHP相关文章