PHP preg_match解析器-如何获取大写字母



我有解析复制粘贴的mediainfo文本并创建数组的代码,但我有一个问题,因为在这段代码中,$line需要小写,否则它不会打印任何内容。

如何使用大写字母?

如果我将其更改为strtoupper代码不再工作。

$line = trim(strtolower($line));

如果我想解析文件名,它总是小写的。

示例:

原件:

我的主页视频.S01.E01.mp4

解析后:

my.home.video.s01.e01.mp4

class Parser {
// Mediainfo 
private $regex_section = "/^(?:(?:general|video|audio|text|menu)(?:s#d+?)*)$/i";
public function parse($string)
{
$string = trim($string);
$lines = preg_split("/rn|n|r/", $string);
$output = [];
foreach ($lines as $line) {
$line = trim(strtolower($line));
if (preg_match($this->regex_section, $line)) {
$section = $line;
$output[$section] = [];
}
if (isset($section)) {
$output[$section][] = $line;
} else {
$output['general'][] = $line;
}
} 

编辑:

完整代码:https://pastebin.com/MkxSYk1W

如果我从该行$line = trim(strtolower($line));中删除strtolower

我打印输出时得到了这个。没有值。

Array ( [general] => [video] => [audio] => [text] => )

如果我理解正确,您希望按节对文件名进行分组。

$filenames = [
'My.Home.Video.S01.E01.mp4',
'my.home.video.s01.e02.mp4',
'My.Home.Audio.S01.E01.mp4'
];
// match specific strings between dots, capture as "section"
$pattern = '(\.(?<section>general|video|audio|text|menu)\.)i';
$output = [];
foreach ($filenames as $filename) {
// default section
$section = 'general';
if (preg_match($pattern, $filename, $match)) {
// lowercase captured section
$section = strtolower($match['section'] ?? 'general');
}
if (isset($output[$section])) {
// add to existing group
$output[$section][] = $filename;
} else {
// add new group
$output[$section] = [$filename];
}

}
var_dump($output);

输出:

array(2) {
["video"]=>
array(2) {
[0]=>
string(25) "My.Home.Video.S01.E01.mp4"
[1]=>
string(25) "my.home.video.s01.e02.mp4"
}
["audio"]=>
array(1) {
[0]=>
string(25) "My.Home.Audio.S01.E01.mp4"
}
}

对文件进行分组可以更加直接/简单。

查找文件";类别";在文件名中的点之间,如果找到,则使用小写匹配类别词作为输出数组中的第一级关键字。如果没有找到白名单中的类别词,那么它就会被推送到通用子数组中。

这里不需要子数组实例化。

代码:(演示(

$filenames = [
'My.Home.Video.S01.E01.mp4',
'my.home.video.s01.e02.mp4',
'My.Home.Audio.S01.E01.mp4'
];
$output = [];
foreach ($filenames as $filename) {
$section = preg_match(
'~.(video|audio|text|menu).~i',
$filename,
$match
)
? strtolower($match[1])
: 'general';
$output[$section][] = $filename;
}
var_export($output);

输出:

array (
'video' => 
array (
0 => 'My.Home.Video.S01.E01.mp4',
1 => 'my.home.video.s01.e02.mp4',
),
'audio' => 
array (
0 => 'My.Home.Audio.S01.E01.mp4',
),
)

专业提示:使用R代替rn|n|r

最新更新