加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

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

发布时间:2020-12-13 16:29:15 所属栏目: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
我希望能够像这样解析文件路径:
/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)'));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读