Replace first two characters of a string in php

Viewed 4723

I am dealing with a problem of time conversion from 12 hr format to 24 hour format.

Is there any single function in php to replace the first two characters of a string?

str_replace can be used only when I know the substring content to be replaced.

2 Answers
$str_to_replace = '12';

$input_str = 'ab345678';

$output_str = $str_to_replace . substr($input_str, 2);

echo $output_str;

"12345678"

If the date is always given in a specific format you could try to convert it to a DateTime object and format the output.

$dateString = '15-Feb-2009 2:24 PM';
$date = DateTime::createFromFormat('j-M-Y g:i A', $dateString);
echo $date->format('Y-m-d G:i'); // will show "2009-02-15 14:24"

In general you should try in avoid holding a date in a string. Convert it to a DateTime -- this makes it also easier for you to manipulate the object (e.g. move date +1 day)

Related