331

Is there a PHP function that can do that?

I'm using strpos to get the position of a substring and I want to insert a string after that position.

Hash
  • 4,647
  • 5
  • 21
  • 39
Alex
  • 66,732
  • 177
  • 439
  • 641
  • An example to [insert a substring in a string at specific index in PHP](https://www.tutorialkart.com/php/php-insert-substring-at-specific-index-in-a-string/) – arjun Dec 18 '22 at 02:51

12 Answers12

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

http://php.net/substr_replace

In the above snippet, $pos is used in the offset argument of the function.

offset
If offset is non-negative, the replacing will begin at the offset'th offset into string.

If offset is negative, the replacing will begin at the offset'th character from the end of string.

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
urmaul
  • 7,180
  • 1
  • 18
  • 13
  • 28
    This should be the accepted answer. Built-in functions take precedence over user-created functions any day. – Benjam Nov 04 '13 at 17:15
  • 14
    Yes, the 4th argument being "0" causes the replaecment string to be inserted without overwriting any of the original string. – Buttle Butkus Feb 07 '14 at 06:40
  • 8
    Brilliant answer. But for lazy people (like me) there should be a short explanation in your post maybe. I'll do it now and copy'n'paste from php.net: "Of course, if length is zero then this function will have the effect of inserting replacement into string at the given start offset." – Wolfsblvt Jan 23 '15 at 23:55
  • 7
    Beware: The function substr_replace() is not multibyte safe! Your $pos may turn out to be in the middle of a UTF-8 character. You may need to employ @tim-cooper's solution but using mb_substr(). – richplane Aug 19 '15 at 14:49
81
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);

substr on PHP Manual

DACrosby
  • 11,116
  • 3
  • 39
  • 51
16

Try it, it will work for any number of substrings

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

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

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

    // bca+++def a+++bcdef
?>
Volker E.
  • 5,911
  • 11
  • 47
  • 64
alexdets
  • 1,473
  • 1
  • 8
  • 3
10

Use the stringInsert function rather than the putinplace function. I was using the later function to parse a mysql query. Although the output looked alright, the query resulted in a error which took me a while to track down. The following is my version of the stringInsert function requiring only one parameter.

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  
user2958137
  • 101
  • 1
  • 3
6

This was my simple solution too append text to the next line after it found the keyword.

$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!!!");

Output:

This is a test
#FINDME#
Insert this awesome string below findme!!!
Other text and data.
Lance Badger
  • 791
  • 8
  • 13
3

Just wanted to add something: I found tim cooper's answer very useful, I used it to make a method which accepts an array of positions and does the insert on all of them so here that is:

EDIT: Looks like my old function assumed $insertstr was only 1 character and that the array was sorted. This works for arbitrary character length.

function stringInsert($str, $pos, $insertstr) {
    if (!is_array($pos)) {
        $pos = array($pos);
    } else {
        asort($pos);
    }
    $insertionLength = strlen($insertstr);
    $offset = 0;
    foreach ($pos as $p) {
        $str = substr($str, 0, $p + $offset) . $insertstr . substr($str, $p + $offset);
        $offset += $insertionLength;
    }
    return $str;
}
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
  • 1
    This does not work. Your offset assumes $interstr to be just 1 character long. You need to add offset depending on insertstr length, start with 0 and add after the substr. Furthermore you should sort the positions low to high to make it work. I corrected your function here, you might want to edit your code: http://pastebin.com/g9ADpuU4 – Matthias S Nov 26 '16 at 16:04
  • @MatthiasS thanks, next time just edit or suggested edit, I didn't notice this til 2 years later – chiliNUT Nov 02 '18 at 15:29
3

I have one my old function for that:

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

This is a small powerful function that performs its job flawlessly.

Ivijan Stefan Stipić
  • 6,249
  • 6
  • 45
  • 78
3
str_replace($sub_str, $insert_str.$sub_str, $org_str);
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • @minitech The op said `using strpos to get the position of a substring`, so the `substring` comes first. And he didn't say find only one position. – xdazz Nov 24 '11 at 02:11
  • 2
    This unexplained answer may make multiple replacements depending on the input strings used. This makes this answer low-value and potentially dangerous to researchers. – mickmackusa Apr 21 '21 at 06:56
2

Strange answers here! You can insert strings into other strings easily with sprintf [link to documentation]. The function is extremely powerful and can handle multiple elements and other data types too.

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

gives you the string

I like green apples.
Sliq
  • 15,937
  • 27
  • 110
  • 143
  • 5
    That's nice. but it does not handle a programmatic approach. We usually have `'I like apples.'` as a variable. So we have to insert `%s` first in the string, which return to the original problem – KeitelDOG Mar 28 '19 at 18:33
  • 3
    This answer ignores the OP's sample input data / scenario. This is the correct answer to a different question. – mickmackusa Apr 21 '21 at 07:00
1

Simple and another way to solve :

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;

}  
jewelhuq
  • 1,210
  • 15
  • 19
1
function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}
Ivan Ivan
  • 51
  • 3
  • `$posEnd` is unneeded. The question was about inserting substring after specified position. – Styx Aug 14 '17 at 15:49
  • Yes, but i made this function for my project. where i needed in some place replacing and in another just inserting. My function is working for this question too, so i cant understand why did you minus me? – Ivan Ivan Aug 21 '17 at 00:00
  • I didn't minus this answer, but it is completely unexplained. Please only post with the intent to be generous and educational. Why should anyone use this answer over another answer? (I know the answer to this; but you should [edit] your question to answer it for researchers.) – mickmackusa Apr 21 '21 at 06:58
  • Because this solution is working and in some case only this solution will be working. Because I was looking at that moment a solution for my task and that solution didn't solve my problem. So I guessed that somebody like me in future will be looking a solution for an equal problem and my solution will help him. – Ivan Ivan Apr 22 '21 at 01:27
0

I'm using these two functions to modify a string:

function insertToString(string $mainstr,string $insertstr,int $index):string
{
    return substr($mainstr, 0, $index) . $insertstr . substr($mainstr, $index);
}

function deleteFromString(string $mainstr, int $index, int $length = 1):string
{
    return substr($mainstr, 0, $index) . substr($mainstr, $index + $length);
}

Enjoy...

MiMFa
  • 981
  • 11
  • 14