1

I have date in following format 07 Dec, 2010. I need to convert it to 07_Dec_2010.

How can I achieve following using single statement

Help appreciated

Thanks

4 Answers 4

1
$newString = preg_replace('/\W+/', '_', $oldString);

This will replace any one or more non-word characters with a single underscore

Sign up to request clarification or add additional context in comments.

2 Comments

does preg_replace have any compatibility issue like it works only on PHP 5 or something else?
@IMJM Best place to check is the manual (also, you don't need to ask the same question more than once)
0
$newdate = preg_replace('/[ ,]+/', '_', '07 Dec, 2010');

5 Comments

does preg_replace have any compatibility issue like it works only on PHP 5 or something else?
@Rafe You're missing the regex delimeters around the pattern
@PhilBrown thanks, that bit of PHP always mixes me up (never really got why that was necessary coming from Python)
@Rafe I hear you. I'd say it's because regular expressions aren't first class citizens in PHP, yet it still needs something to pass to the PCRE engine
@PhilBrown regex aren't first class in Python either, but you can just pass a string to a regex function and it works that way. Dunno, a lot of the quirks of PHP syntax make no sense to me (why make everything ugly by requiring a sigil for a variable). It's all old perl stuff
0
$newdate = str_replace( ' ', '_', str_replace( ',','', "07 Dec, 2010" ) );

Edit:

$newdate = str_replace( array(',' , ' '), array('' , '_'), "07 Dec, 2010" );

5 Comments

@downvoter: I will feel happy if you will tell me a reason and I will learn something new.
@pinaki: Are you sure? , is removed before replacing space with _. codepad.org/d15A7aDd
@pinaki: You still did not justify your comments.
@NAVEED - you are right.. i think i confused the second blank with a underscore the other night; extremely sorry about that. On another note, i agree this does what is required, but is it one line? The OP wanted the change in a "single statement" and you have two statements there. I am not sure having multiple function calls in one-line can be termed as a single statement.
@pinaki: Ok. I have edited my answer. Will you consider it as a single statement.
0

Try this:

echo date('d_M_Y',strtotime('07 Dec, 2010'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.