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

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


当前回答

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

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

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

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

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

其他回答

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

PHP手册中的substr

str_replace($sub_str, $insert_str.$sub_str, $org_str);

简单的另一种解决方法:

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;

}  

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

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

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

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

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

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

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