PHP如何在特定位置将多个字符串添加到另一个字符串

时间:2016-07-21 08:05:37

标签: php

我在PHP中有变量的字符串,如:

$datetime="20160105 1134";

我想调用一些简单的函数来在某些位置添加某些字符串。获得

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

我知道我可以使用substr()这样做,但有没有最简单的解决方案,只需告诉PHP将“ - ”放在第4和第6位并将“:”放在第11位?我为此编写了自己的函数,但我问这是否可能更容易,例如。使用正则表达式。

// 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

3 个答案:

答案 0 :(得分:0)

这很简单吗?

$datetime="20160105 1134";
$datetime = date('Y-m-d H:i:s',strtotime($datetime));
echo $datetime;

答案 1 :(得分:0)

试试这个method

$newstr = substr_replace($oldstr, $str_to_insert, $pos, 0);

答案 2 :(得分:0)

好的,这里使用正则表达式

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

类似地

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