Insert string at specified position

PhpString

Php Problem Overview


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.

Php Solutions


Solution 1 - Php

$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.

Solution 2 - Php

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

substr on PHP Manual

Solution 3 - Php

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

Solution 4 - Php

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;
}  

Solution 5 - Php

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.

Solution 6 - Php

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

Solution 7 - Php

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;
}

Solution 8 - Php

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.

Solution 9 - Php

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;
  
}  

Solution 10 - Php

function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}

Solution 11 - Php

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - PhpurmaulView Answer on Stackoverflow
Solution 2 - PhpTim CooperView Answer on Stackoverflow
Solution 3 - PhpalexdetsView Answer on Stackoverflow
Solution 4 - Phpuser2958137View Answer on Stackoverflow
Solution 5 - PhpLance BadgerView Answer on Stackoverflow
Solution 6 - PhpxdazzView Answer on Stackoverflow
Solution 7 - PhpchiliNUTView Answer on Stackoverflow
Solution 8 - PhpIvijan Stefan StipićView Answer on Stackoverflow
Solution 9 - PhpjewelhuqView Answer on Stackoverflow
Solution 10 - PhpIvan IvanView Answer on Stackoverflow
Solution 11 - PhpSliqView Answer on Stackoverflow