失眠网,内容丰富有趣,生活中的好帮手!
失眠网 > php 匹配多个正则表达式 php – 正则表达式匹配无限数量的选项

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

时间:2023-10-12 06:49:18

相关推荐

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.

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

$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)'));

总结

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。

如果觉得《php 匹配多个正则表达式 php – 正则表达式匹配无限数量的选项》对你有帮助,请点赞、收藏,并留下你的观点哦!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。