Tomas M Tomas M - 4 months ago 10
PHP Question

PHP how to add multiple strings to another string at certain positions

I have string in PHP in variable, like:

$datetime="20160105 1134";


I would like to call some simple function to add certain strings at certain positions. To get

$datetime="2016-01-05 11:34";


I know I can do it with substr() and such, but is there any simplest solution, which would simply tell PHP to put "-" at positions 4 and 6 and to put ":" at position 11? I wrote my own function for this, but I'm asking if this is somehow possible more easily eg. using regex or so.

// my function
function put($what,$pos,$txt)
{
if (!is_array($pos)) $pos=[$pos]; rsort($pos);
foreach($pos as $p) $txt=substr($txt,0,$p).$what.substr($txt,$p);
return $txt;
}

$datetime=put("-",[4,6],put(":",11,$datetime));
// result: 2016-01-05 11:34

Answer

OK here is using regex

$datetime="20160105 1134";
$datetime=preg_replace("{^(....)(..)(..)(...)}","\\1-\\2-\\3\\4:",$datetime);

similarly

$var="test string";
$var=preg_replace("^(....)(.)(......)","\\1-\\3",$var);
Comments