3

I have a string, for example

20120201

I need to change it to

2012/02/01

obviously I need to add "/" after the 4th, 6th characters in the string.

Could someone help me do this in PHP?

Thank you.

3
  • did you try substring? Also you could try php.net/manual/en/function.strtotime.php if it is always date Commented Feb 28, 2012 at 13:47
  • I've been looking for a suitable method to do this and havn't found any (probably because of my lack of experience). I had a look at substring, I couldn't figure out how to use it with this specific example I need. Commented Feb 28, 2012 at 13:50
  • The direct answer to your question is the substr answers you've seen below, but if it is always a date you're talking about, the better answer is the strtotime function mentioned by others. It's more clear when you see your code later or someone else has to code behind you, what you were doing and why. (Trust me, 2 years from now, you'll be glad you did it.) Commented Feb 28, 2012 at 15:02

4 Answers 4

7

Something like this:

$final = substr($initial,0,4).'/'.substr($initial,4,2).'/'.substr($initial,6,2)

Use substr.

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

2 Comments

For info sake, the last ,2 is not required as substr will go to the end if the length isn't given
Thakns for info, didn't know.
3

You could use substr, something like

$result = substr($str,0,4)."/".substr($str,4,2)."/".substr($str, 6)

edit: Messing between Java and Php for String concat :p

1 Comment

you mean "." instead of "+" .. this is PHP not java(script). FTFY.
1

If you want inserting, you can use http://php.net/substr_replace

$string = "20120201";
$newString = substr_replace(substr_replace($string, "/", 6, 0), "/", 4, 0);

or concatenate substrings got by http://php.net/substr

$newString = substr($string, 0, 4) . "/" . substr($string, 4, 2) . "/" . substr($string, 6)

Comments

1

You could use date_parse_from_format to parse the date you have there into a PHP date object, then you could output it in any format you'd like. A list of available date formats is located here

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.