从 PHP 中的字符串中删除日期
Removing date from string in PHP
我正在尝试使用 preg_replace() 从 PHP 中的字符串中删除所有日期。日期格式如下:YYYY-MM-DD、YYYY/MM/DD 或 YYYY.MM.DD
$string1 = "Current from 2014-10-10 to 2015-05-23";
$output = preg_replace('/\d{4}[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])/g', '', $string1);
预期输出为 "Current from to "。目前我正在返回“”。
非常感谢任何帮助!旺科
这应该有效。
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.02.10";
$output = preg_replace('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', '', $input);
echo $output;
更新
确保日期也有效
<?php
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.19.10";
$output = preg_replace_callback('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', function($matches) {
$date = str_replace(array('.','/'), '-', $matches[1]);
$newDate = DateTime::createFromFormat('Y-m-d', $date);
if($newDate->format('Y-m-d') == $date) {
return false;
}else {
return $matches[1];
}
}, $input);
echo $output;
我正在尝试使用 preg_replace() 从 PHP 中的字符串中删除所有日期。日期格式如下:YYYY-MM-DD、YYYY/MM/DD 或 YYYY.MM.DD
$string1 = "Current from 2014-10-10 to 2015-05-23";
$output = preg_replace('/\d{4}[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])/g', '', $string1);
预期输出为 "Current from to "。目前我正在返回“”。
非常感谢任何帮助!旺科
这应该有效。
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.02.10";
$output = preg_replace('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', '', $input);
echo $output;
更新 确保日期也有效
<?php
$input = "Current from 2014-10-10 to 2015/05/23 and 2001.19.10";
$output = preg_replace_callback('/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/', function($matches) {
$date = str_replace(array('.','/'), '-', $matches[1]);
$newDate = DateTime::createFromFormat('Y-m-d', $date);
if($newDate->format('Y-m-d') == $date) {
return false;
}else {
return $matches[1];
}
}, $input);
echo $output;