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

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


当前回答

简单的另一种解决方法:

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;

}  

其他回答

奇怪的答案!您可以使用sprintf[文档链接]轻松地将字符串插入到其他字符串中。这个函数非常强大,可以处理多个元素和其他数据类型。

$color = 'green';
sprintf('I like %s apples.', $color);

给你字符串

I like green apples.

我有一个老函数

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

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

使用stringInsert函数,而不是putinplace函数。我使用后面的函数来解析mysql查询。虽然输出看起来不错,但查询导致了一个错误,我花了一段时间才找到。下面是只需要一个形参的stringInsert函数的版本。

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  

试试吧,它对任意数量的子字符串都有效

<?php
    $string = 'bcadef abcdef';
    $substr = 'a';
    $attachment = '+++';

    //$position = strpos($string, 'a');

    $newstring = str_replace($substr, $substr.$attachment, $string);

    // bca+++def a+++bcdef
?>

简单的另一种解决方法:

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;

}