2

I have a date in this format (extracted from a specific script), on which I'd like to remove ALL spaces :

$date="Date:         Tue Aug  2 10:43"

Quite easy, but the trick is: prior to this, I'd like to add a "0" before the "2" (or any other 9th first days of the month), BUT the "0" has to replace the second space between "Aug" and "2". What is the best way to achieve this ?

Keep in mind that the date will (obviously) change each day, so we can't simply do something like this:

$date=str_replace("Aug  2","Aug 02",$date);

Instead, I think the best way would be to do something like:

$date=str_replace("[x]  [x]","[x] 0[x]",$date);

[x] meaning: "Any non-whitespace character" (please excuse me for this approximation !)

4 Answers 4

3

use date() and strtotime() to do this mission

$date = strtotime('Tue    Aug     2 10:43'); //white spaces won't effect
echo date('D M 0\2 h:i',$date); 
// output the date just replace the 2 with your 9th of month letter 
Sign up to request clarification or add additional context in comments.

1 Comment

Must be the "nicest" solution of all, but, in this specific case, Akremon solution suited me just fine, as it was the easiest for me to implement. Many thanks for you help anyway !
1

Hm, maybe thet solution?

$date=preg_replace("/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)  (\d)(\s+)/","$1 0$2$3",$date);

1 Comment

Maybe not the "nicest" solution, but actually the simplest to implement into my code. Worked like intended. Many Thanks !
1

I saw two possibilities :

Comments

1

Looking at your input data, it seems that your specific script produces a formatted output - meaning that it uses padding with spaces. This means that probably the length of the string is always the same - regardless of the actual date and time in it. If this is true, then you can use a very simple code:

if($date{22} == ' ') $date{22} = '0'; // replace space with zero
$date = preg_replace('/  +/', ' ', $date); // convert multiple spaces into single space

However, if your specific script does not produce a formatted otput then you will have to use something little different, but again very simple:

$date = preg_replace('/  +/', ' ', $date); // convert multiple spaces into single space
$arr = explode(' ', $date); // split text into words by spaces
if($arr[3] < 10) $arr[3] = '0'.$arr[3];
$date = implode(' ', $arr); // combine words

1 Comment

I used Lakremon solution, but thanks anyway for your comment and your time, hope it shall help somedy in the future.

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.