preg_replace 和日期
我想删除日期字符串中的所有 -
和 /
字符。有人可以帮我吗?
这是我所拥有的,但它不起作用。
preg_replace('/','',$date);
preg_replace('-','',$date);
另外,有没有办法将这两个表达式组合在一起,这样我就不必有 2 个 preg_replaces 了?
I want to remove all -
and /
characters in a date string. Can someone give me a hand?
Here is what I have but it doesn't work.
preg_replace('/','',$date);
preg_replace('-','',$date);
Also, is there a way to group these two expressions together so I don't have to have 2 preg_replaces?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
使用
$date = str_replace(aray('/','-'),'',$date);
也快得多。use
$date = str_replace(aray('/','-'),'',$date);
It's also much faster.使用“翻译”方法代替正则表达式。在 PHP 中,这将是
strtr()
Instead of a regex, use a 'translate' method. In PHP, that would be
strtr()
是的!您需要仔细查看 手动。
以下是使用
preg_replace()
的示例:Yes! You need to take a closer look at the examples of
$pattern
in the manual.Here's an example using
preg_replace()
:我认为
[/\-]
是最有效的。[/\-]
is the most efficient, I think.由于您要将一个字符替换为另一个字符,因此基于正则表达式的解决方案是一种矫枉过正。您可以使用
str_replace
如下:您的
preg_replace
出了什么问题?preg_replace
期望正则表达式被一对分隔符包围。所以这应该有效:同样,与
str_replace
一样,preg_replace
也接受数组,因此您可以这样做:您还可以将要在单个正则表达式中删除的两个模式组合起来,如下所示:
Since you are replacing one character with another character, a regex based solution is an overkill. You can just use
str_replace
as:Now what was wrong with your
preg_replace
?preg_replace
expects the regex to be surrounded by a pair of delimiters. So this should have worked:Also as
str_replace
,preg_replace
also accepts arrays, so you can do:Also you can combine the two patterns to be removed in a single regex as: