PHP:替换数组中不存在的所有单词
我正在尝试使用 PHP 解析用户输入的字符串日期。我需要删除除这两个可接受的类别之外的所有字符:
1) [0-9,\./-] (numerals, comma, period, slash, and dash)
2) An array of acceptable words:
$monthNames=array(
"january"=>1,
"jan"=>1,
"february"=>2,
"feb"=>2
);
我尝试对字符单词边界进行explode()ing,然后删除不在数组中的每个部分,但这导致了相当混乱。有没有一种优雅的方法来实现这一点?
谢谢!
I am trying to parse user-entered string dates with PHP. I need to remove all characters other than these two acceptable categories:
1) [0-9,\./-] (numerals, comma, period, slash, and dash)
2) An array of acceptable words:
$monthNames=array(
"january"=>1,
"jan"=>1,
"february"=>2,
"feb"=>2
);
I tried explode()ing on character word bounaries and then removing each section that is not in the array, but that led to quite a mess. Is there an elegant way of accomplishing this?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用
strtotime()
检查是否失败:
请参阅 http: //php.net/manual/en/function.strtotime.php
另外,
DateTime::createFromFormat()
可能会有用。请参阅http://www.php.net/manual/en/datetime.createfromformat。 php
You could use
strtotime()
To check for failure:
See http://php.net/manual/en/function.strtotime.php
Also
DateTime::createFromFormat()
might be useful.See http://www.php.net/manual/en/datetime.createfromformat.php
避免这种情况的最佳方法是将日期条目设置为仅包含有效选项的表单,并丢弃其余选项。
Best way to avoid that would be to make the date entry a form with only valid option and discard the rest.
您可以使用正则表达式来匹配日期,这是一个非常简单、基本的表达式:
不过,您必须添加其他月份。
不眠之夜的进一步想法:
我会采取两步方法:
You could use a regulare expression to match dates, here's a very simplistic, rudimentary one:
You'll have to add the other months, though.
Further ideas for sleepless nights:
I'd take a two step approach:
如果可以安全地假设您的 $monthNames 数组少于 26 个元素,那么以下方法有效(尽管这绝对是一个“黑客” - 如果我能想到一些东西,我会提供另一个答案值得被称为“优雅”):
注意:
If it is safe to assume that your $monthNames array has less than 26 elements, then the following works (though this is definitely a "hack" - I'll offer another answer if I can think of something which deserves to be called "elegant"):
NOTES: