有没有PHP函数可以做到这一点?

我使用strpos来获取子字符串的位置,我想在该位置之后插入一个字符串。


当前回答

这是我的简单解决方案,太追加文本到下一行后,它找到关键字。

$oldstring = "This is a test\n#FINDME#\nOther text and data.";

function insert ($string, $keyword, $body) {
   return substr_replace($string, PHP_EOL . $body, strpos($string, $keyword) + strlen($keyword), 0);
}

echo insert($oldstring, "#FINDME#", "Insert this awesome string below findme!!!");

输出:

This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.

其他回答

$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);

PHP手册中的substr

简单的另一种解决方法:

function stringInsert($str,$insertstr,$pos)
{
  $count_str=strlen($str);
  for($i=0;$i<$pos;$i++)
    {
    $new_str .= $str[$i];
    }

    $new_str .="$insertstr";

   for($i=$pos;$i<$count_str;$i++)
    {
    $new_str .= $str[$i];
    }

  return $new_str;

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

http://php.net/substr_replace

在上面的代码片段中,$pos用于函数的offset参数。

offsetIf偏移量非负,替换将从 偏移到字符串的偏移量。 如果偏移量为负,则替换将从偏移量开始 字符串末尾的字符。

我有一个老函数

function putinplace($string=NULL, $put=NULL, $position=false)
{
    $d1=$d2=$i=false;
    $d=array(strlen($string), strlen($put));
    if($position > $d[0]) $position=$d[0];
    for($i=$d[0]; $i >= $position; $i--) $string[$i+$d[1]]=$string[$i];
    for($i=0; $i<$d[1]; $i++) $string[$position+$i]=$put[$i];
    return $string;
}

// Explanation
$string='My dog dont love postman'; // string
$put="'"; // put ' on position
$position=10; // number of characters (position)
print_r( putinplace($string, $put, $position) ); //RESULT: My dog don't love postman

这是一个功能强大的小函数,它完美地完成了自己的工作。

这是我的简单解决方案,太追加文本到下一行后,它找到关键字。

$oldstring = "This is a test\n#FINDME#\nOther text and data.";

function insert ($string, $keyword, $body) {
   return substr_replace($string, PHP_EOL . $body, strpos($string, $keyword) + strlen($keyword), 0);
}

echo insert($oldstring, "#FINDME#", "Insert this awesome string below findme!!!");

输出:

This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.