我有一些像
这样的字符串$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.
我想创建一个除去年份以外的所有数字和汽车“模型”的功能。 我不知道如何确定数字是一年,还是型号或身份证。 谢谢
答案 0 :(得分:0)
我想你可以删除所有从19和20开始的4位数字(如果汽车不超过2000,则只有20)和字符串中最后一个点之前的数字(如果有的话)...但是谁知道你提供的信息是否100%准确(缺少命名模式)。
答案 1 :(得分: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>";
}