-1

我有一些字符串,比如

$str1 = "Audi-TT-RS-2012-widescreen-77.jpg";
$str2 = "Audi-R8-widescreen-039.jpg";
$str3 = "2008-bmw-6-series-front-and-side.jpg";
$str4 = "Opel_tigra_2-doors-21313.jpg"; //where 21313 is an id that want to be removed also.

我想创建一个函数来删除除年份和汽车“型号”之外的所有数字。我不知道如何准确检测数字是年份、型号还是 ID。谢谢

4

2 回答 2

0

我想你可以删除所有以 19 和 20 开头的 4 位数字(如果汽车不超过 2000 年,则只有 20)和字符串中最后一个点之前的数字(如果有的话)......但谁知道它是否您提供的信息将 100% 准确(缺乏命名模式)。

于 2013-01-25T02:36:54.813 回答
0
$str1 = "Audi-TT-RS-2012-widescreen-77.jpg";
$str2 = "Audi-R8-widescreen-039.jpg";
$str3 = "2008-bmw-6-series-front-and-side.jpg";
$str4 = "Opel_tigra_2-doors-21313.jpg";
$strs = array($str1, $str2, $str3, $str4);
foreach ($strs as $str) {
    preg_match_all('/(?<!\d)(\d{4})(?!\d)\-*/', $str, $matches);
    foreach ($matches[1] as $year) {
        if (abs($year - date("Y")) < 100) {
            // this is within 100 years
        }
    }
}

删除号码

$str1 = "Audi-TT-RS-2012-widescreen-77.jpg";
$str2 = "Audi-R8-widescreen-039.jpg";
$str3 = "2008-bmw-6-series-front-and-side.jpg";
$str4 = "Opel_tigra_2-doors-21313.jpg";
$strs = array($str1, $str2, $str3, $str4);
foreach ($strs as $str) {
    preg_match_all('/(?<!\d)(\d{4})(?!\d)\-*/', $str, $matches);
    foreach ($matches[1] as $year) {
        if (abs($year - date("Y")) < 100) {
            $str =  preg_replace('/(?<!\d)(\d{4})(?!\d)/', '[year]', $str);
        }
    }
    preg_match_all('/(?<!\d)(\d{1})(?!\d)\-*/', $str, $matches);
    foreach ($matches[1] as $model) {
        $str =  preg_replace('/(?<!\d)(\d{1})(?!\d)/', '[model]', $str);
    }

    preg_match_all('/\-*(\d+)\-*/', $str, $matches);
    foreach ($matches[1] as $id) {
        $str =  preg_replace('/\-*(\d+)\-*/', '', $str);
    }
    $str =  preg_replace('/\[year\]/', $year, $str);
    $str =  preg_replace('/\[model\]/', $model, $str);
    echo $str."<br>";
}
于 2013-01-25T02:45:44.977 回答