我很高兴这个论坛存在,因为我不知道还有什么地方可以解决这个问题。我正在使用preg_match_all()解析PHP中一大堆文件的文件名,我希望恢复4位信息。命名约定是:
_tag_99_Nice_name.extension
我需要将其分解为4个部分
棘手的部分是前3个是可选的,可能存在也可能不存在,因此以下任何一个都是有效的例子:
_taggy_01_foo_bar.text
69_something.gif
_tag_some_thing.jpg
basic.example
到目前为止,我最好的尝试是:
/^(?:_+(?P<tag>[a-z0-9]+)*_)?(?:(?P<sort>\d{2})_)?/
但这只是不起作用,只试图抓住前两部分:(
任何想法都会有很大的帮助!
答案 0 :(得分:2)
更新:适用于所有示例案例(以及多个文件扩展名)。
<?php
$pattern = "~^(?:_(?P<tag>[A-Za-z0-9]+)_)?(?:(?P<sort>\d{2})?_)?(?P<name>\w+)(?P<ext>[.]\w+)+$~";
$tests = array(
"_taggy_01_foo_bar.text",
"69_something.gif",
"_tag_some_thing.jpg",
"basic.example",
"_loltag_00_pretty_name.extone.exttwo.extthree"
);
foreach ($tests as $item) {
preg_match($pattern, $item, $matches);
print_r($matches);
}
?>
<强>输出:强>
Array
(
[0] => _taggy_01_foo_bar.text
[tag] => taggy
[1] => taggy
[sort] => 01
[2] => 01
[name] => foo_bar
[3] => foo_bar
[ext] => .text
[4] => .text
)
Array
(
[0] => 69_something.gif
[tag] =>
[1] =>
[sort] => 69
[2] => 69
[name] => something
[3] => something
[ext] => .gif
[4] => .gif
)
Array
(
[0] => _tag_some_thing.jpg
[tag] => tag
[1] => tag
[sort] =>
[2] =>
[name] => some_thing
[3] => some_thing
[ext] => .jpg
[4] => .jpg
)
Array
(
[0] => basic.example
[tag] =>
[1] =>
[sort] =>
[2] =>
[name] => basic
[3] => basic
[ext] => .example
[4] => .example
)
Array
(
[0] => _loltag_00_pretty_name.extone.exttwo.extthree
[tag] => loltag
[1] => loltag
[sort] => 00
[2] => 00
[name] => pretty_name
[3] => pretty_name
[ext] => .extthree
[4] => .extthree
)
答案 1 :(得分:1)
'~^(?:_(?<tag>\w+)_)?(?:(?<sort>\d{2})_)?(?<name>[^.]+)\.(?<ext>\w+)$~'
但我不确定,我是否理解,它是可选的,什么不是。
答案 2 :(得分:1)
这个怎么样:
^(_(?P<tag>.*?)_)?((?P<sort>\d\d)_)?(?P<name>[^.]*)?.*([.](?P<ext>[^.]*))$