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) 对不起,我没有马上说出来.
非正则表达式解决方案:)
<?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)')); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |