我希望能够将电视连续剧的剧集从#7.11
转换为S07E11
例如,我有字符串Monk #7.11
或Family Guy #5.6
我想应用正则表达式/函数,而是接收Monk S07E11
或Family Guy S05E06
。
答案 0 :(得分:3)
function convert($matches) {
$season = str_pad($matches[1], 2, "0", STR_PAD_LEFT);
$episode = str_pad($matches[2], 2, "0", STR_PAD_LEFT);
return "S" . $season . "E" . $episode;
}
echo preg_replace_callback("/#(\d+)\.(\d+)/", "convert", "Monk #7.11");
// Monk S07E11
echo preg_replace_callback("/#(\d+)\.(\d+)/", "convert", "Family Guy #5.6");
// Family Guy S05E06
它允许您提供用于转换输入的函数回调。
<强> DEMO 强>
答案 1 :(得分:2)
<?php
$regex="/^([^#]+?) *#([0-9]+)\.([0-9]+)$/";
$fmt="%s S%02dE%02d\n";
$items=array(
"Family Guy #5.6",
"Monk #7.11",
);
foreach ($items as $one) {
preg_match($regex, $one, $matches);
printf($fmt, $matches[1], $matches[2], $matches[3]);
}
返回:
Family Guy S05E06
Monk S07E11
答案 2 :(得分:1)
PHP代码:
$s = 'Monk #7.11';
$p = '/^([^#]+\s)#(\d+)\.(\d+)$/e';
$r = 'sprintf("%sS%02dE%02d", "$1", "$2", "$3")';
echo preg_replace($p, $r, $s);
输出:
Monk S07E11
测试此代码here。