views:

18

answers:

5

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?

+1  A: 

use $date = str_replace(aray('/','-'),'',$date); It's also much faster.

ts
Thanks ts. THat works. I'll give you the credit here in 4 minutes as it won't let me accept prior to that
chad
+1  A: 

Instead of a regex, use a 'translate' method. In PHP, that would be strtr()

strtr( $date, '/-', '' );
Blackcoat
A: 

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
Johnsyweb
A: 

[/\-] is the most efficient, I think.

Vantomex
A: 

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);
codaddict