替换数字和单词

时间:2011-08-17 18:43:32

标签: php str-replace string

如何从这个模式'name season 1 episode 2'中更改字符串,= ='name S01E02' - 但是如果有超过10的情节,就像'名称第1季第15集'那样,只有季节会改变,我试着这样做:

<?php
$trans = array(
    ' season'   =>      ' S',
    ' 1'        =>      ' 01',
    ' 2'        =>      ' 02',
    ' 3'        =>      ' 03',
    ' 4'        =>      ' 04',
    ' 5'        =>      ' 05',
    ' 6'        =>      ' 06',
    ' 7'        =>      ' 07',
    ' 8'        =>      ' 08',
    ' 9'        =>      ' 09',
    ' episode'      =>      ' E'
);
$q = strtr($q, $trans);


$trans = array(
    'S '        =>      'S',
    ' E '       =>      'E'
);
$q = strtr($q, $trans);
?>

2 个答案:

答案 0 :(得分:2)

$string = 'name season 1 episode 2';
if (preg_replace('/(.*?) season (\d+) episode (\d+)/', $string, $matches) {
     $new_name = sprintf('%s S%02dE%02', $matches[1], $matches[2], $matches[3]);
}

应该使new_name ='name S01E02',假设您的名字与格式和内部结构一致。

答案 1 :(得分:0)

$original_string = "some_thing season 1 episode 9";
preg_replace("/([^ ]*) season ([\d]) episode ([\d])/", "$1 S0$2E0$3", $original_string);