Reputation: 23
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?
Upvotes: 2
Views: 4047
Reputation: 455000
Since you are replacing one character with another character, a regex based solution is an overkill. You can just use str_replace
as:
$edited_date = str_replace(array('/','-'),'',$date);
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:
$edited_date = preg_replace('#-#','',$date);
Also as str_replace
, preg_replace
also accepts arrays, so you can do:
$from = array('#/#','#-#');
$to = '';
$edited_date = preg_replace($from,$to,$date);
Also you can combine the two patterns to be removed in a single regex as:
$edited_date = preg_replace('#-|/#','',$date);
Upvotes: 0
Reputation: 141790
Yes! You need to take a closer look at the examples of $pattern
in the manual.
Here's an example using preg_replace()
:
#!/usr/bin/env php
<?
$date = "2009/08/07";
echo "Before: ${date}\n";
$date = preg_replace('/[-\/]/', '', $date);
echo "After: ${date}\n";
$date = "2009-08-07";
echo "Before: ${date}\n";
$date = preg_replace('/[-\/]/', '', $date);
echo "After: ${date}\n";
?>
% ./test.php
Before: 2009/08/07
After: 20090807
Before: 2009-08-07
After: 20090807
Upvotes: 0
Reputation: 3310
Instead of a regex, use a 'translate' method. In PHP, that would be strtr()
strtr( $date, '/-', '' );
Upvotes: 2
Reputation: 10709
use $date = str_replace(aray('/','-'),'',$date);
It's also much faster.
Upvotes: 4