首页 > 解决方案 > 从字符串中删除除日期之外的所有数字

问题描述

我需要阻止字符串中除日期之外的所有数字

我尝试了一些正则表达式,但我不知道如何排除

示例字符串

2017年 2 月 8 日[或 2017 年 2 月 8 日或 2017 年 8 月 2 日]发送电子邮件请求回电以安排访问。Jane Doe 17 岁,她的电话号码是 8373763545 Jane Doe 写于 2019 年 4 月 3 日 12:19:我住在纽约 123 街

我试过了/(\d{4}[\.\/\-][01]\d[\.\/\-][0-3]\d)/

但我不知道如何排除日期并阻止其他数字

我需要

2017年 2 月 8 日[或 2017 年 2 月 8 日或 2017 年 8 月 2 日]发送电子邮件请求回电以安排访问。Jane Doe ** 岁,她的电话号码是 ******** Jane Doe 写于 2019 年 4 月 3 日 12:19:我住在纽约街头 ***

标签: php

解决方案


您可能需要根据需要修改代码,但我希望以下是一个好的开始:

// 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"

推荐阅读