如何从 "F d, Y" 格式的字符串中删除日期?
How to remove date from string in "F d, Y" format?
我需要从 F d, Y
格式的字符串中删除所有日期。例如,这一行:
Act current to May 30, 2015
Act current to June 1, 2015
应该变成这样:
Act current to
Act current to
这是我一直在使用的代码:
$input = "Act current to May 30, 2015";
$output = preg_replace('/([January|February|March|April|May|June|July|August|September|October|November|December] [0-3]\d, \d{4})/', '', $input);
echo "$output\n";
输出不是我所期望的:
Act current to Ma
Act current to June 1, 2015
我认为我的部分问题是 [0-3]\d
期望日部分采用 NN
格式,但输入可能采用 N
.
这应该适合你:
在这里,我首先创建一个包含所有月份名称的数组。然后你可以在你的正则表达式模式中使用这个数组。
$str = "Act current to May 30, 2015"; //Act current to June 1, 2015
$months = array_map(function($v){
return date("F", strtotime("2000-" . $v . "-1"));
}, range(1, 12));
echo $str = preg_replace("/(" . implode("|", $months) .")\s\d{1,2},\s\d{4}/", "", $str);
正则表达式解释:
(your|months|separated|by|a|pipe)\s\d{1,2},\s\d{4}/
- 第一个捕获组
- 你所有月份中的一个月
- \s 匹配任意白色 space 字符 [\r\n\t\f ]
- \d{1,2}匹配一个数字[0-9]
- 量词:{1,2}1到2次之间,尽量多,按需回馈[贪心]
- ,匹配字符,字面意思
- \s 匹配任意白色 space 字符 [\r\n\t\f ]
- \d{4}匹配一个数字[0-9]
- 量词:{4} 恰好 4 次
正如您所建议的,部分正则表达式存在问题,此正则表达式对您有用:
preg_replace('/(January|February|March|April|May|June|July|August|September|October|November|December) [1-31]+, \d{4}/', '', $input);
我需要从 F d, Y
格式的字符串中删除所有日期。例如,这一行:
Act current to May 30, 2015
Act current to June 1, 2015
应该变成这样:
Act current to
Act current to
这是我一直在使用的代码:
$input = "Act current to May 30, 2015";
$output = preg_replace('/([January|February|March|April|May|June|July|August|September|October|November|December] [0-3]\d, \d{4})/', '', $input);
echo "$output\n";
输出不是我所期望的:
Act current to Ma
Act current to June 1, 2015
我认为我的部分问题是 [0-3]\d
期望日部分采用 NN
格式,但输入可能采用 N
.
这应该适合你:
在这里,我首先创建一个包含所有月份名称的数组。然后你可以在你的正则表达式模式中使用这个数组。
$str = "Act current to May 30, 2015"; //Act current to June 1, 2015
$months = array_map(function($v){
return date("F", strtotime("2000-" . $v . "-1"));
}, range(1, 12));
echo $str = preg_replace("/(" . implode("|", $months) .")\s\d{1,2},\s\d{4}/", "", $str);
正则表达式解释:
(your|months|separated|by|a|pipe)\s\d{1,2},\s\d{4}/
- 第一个捕获组
- 你所有月份中的一个月
- \s 匹配任意白色 space 字符 [\r\n\t\f ]
- \d{1,2}匹配一个数字[0-9]
- 量词:{1,2}1到2次之间,尽量多,按需回馈[贪心]
- ,匹配字符,字面意思
- \s 匹配任意白色 space 字符 [\r\n\t\f ]
- \d{4}匹配一个数字[0-9]
- 量词:{4} 恰好 4 次
正如您所建议的,部分正则表达式存在问题,此正则表达式对您有用:
preg_replace('/(January|February|March|April|May|June|July|August|September|October|November|December) [1-31]+, \d{4}/', '', $input);