Tomas M Tomas M - 8 months ago 23
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;

// result: 2016-01-05 11:34


OK here is using regex

$datetime="20160105 1134";


$var="test string";