我需要屏蔽字符串中除日期以外的所有数字
我尝试了一些正则表达式,但是我不知道如何排除
示例字符串
02/08/2017 [或02-08-2017或02.08.2017] 发送了电子邮件,要求回电以安排访问。 Jane Doe今年17岁,她的电话号码是8376763545 简·多伊(Jane Doe)在2019年4月3日12:19写道:我住在纽约的123街
我尝试过/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/
但是我不知道如何排除日期并阻止其他数字
我需要
02/08/2017 [或02-08-2017或02.08.2017] 发送了电子邮件,要求回电以安排访问。 Jane Doe **岁,她的电话是******** 简·多伊(Jane Doe)在2019年4月3日12:19写道:我住在纽约的***街上
答案 0 :(得分:0)
您可能需要根据需要修改代码,但我希望以下是一个好的开始:
// Your text
$text = '02/08/2017 [or 02-08-2017 or 02.08.2017] sent email requesting call back to schedule a visit. Jane Doe is 17 years old and her phone number is 8373763545 Jane Doe wrote 3rd April 2019 12:19 : i live in street 123 in New York';
// To avoid inaccuracies specify a list of possible date formats
// For more details see https://www.php.net/manual/en/function.date.php
$date_formats = [
'd/m/Y',
'd.m.Y',
'd-m-Y',
'jS F Y H:i'
];
// Define expressions that must match the string containing a date
$date_long_expr = '\d{1,2}(st|nd|rd|th) [a-z]{3,9} \d{4} \d{2}:\d{2}';
// In order do not to match a date inside some number, capture a wide range of numeric values
$date_short_expr = '[\d./-]+';
// When defining the regex, make sure to use expressions in descending order of their length
// This is necessary to prevent the replacement of characters that can be used by longer ones
$rgxp = "#$date_long_expr|$date_short_expr#i";
// Start the search and replace process
$text = preg_replace_callback($rgxp, function($m) use($date_formats) {
foreach ($date_formats as $format) {
// Each date or numeric value found will be converted to DateTime instance
$dt = date_create_from_format($format, $m[0]);
// Consider it a valid date only if the found value is equal to value returned by DateTime instance
if ($dt && $dt->format($format) == $m[0]) {
return $m[0];
}
}
// Hide digits if the value does not match any date format
return preg_replace('#\d#', '*', $m[0]);
}, $text);
echo $text; //-> "02/08/2017 [or 02-08-2017 or 02.08.2017] sent email requesting call back to schedule a visit. Jane Doe is ** years old and her phone number is ********** Jane Doe wrote 3rd April 2019 12:19 : i live in street *** in New York"