Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert string at specified position

Tags:

string

php

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.

like image 633
Alex Avatar asked Nov 24 '11 02:11

Alex


People also ask

How do you insert a character in a string at a certain position?

One can use the StringBuffer class method namely the insert() method to add character to String at the given position. This method inserts the string representation of given data type at given position in StringBuffer. Syntax: str.

How do you add a string to a specific position in Python?

If you need to insert a given char at multiple locations, always consider creating a list of substrings and then use . join() instead of + for string concatenation. This is because, since Python str are mutable, + string concatenation always adds an aditional overhead.

Which of the following method inserts a string at a specified index position?

The splice() method is used to insert or replace contents of an array at a specific index. This can be used to insert the new string at the position of the array. It takes 3 parameters, the index where the string is to be inserted, the number of deletions to be performed if any, and the string to be inserted.

How do I add a character to a string in PHP?

If you want a very simple and short solution to insert string into another string use: substr_replace ( $string , $replacement , $start , 0 ). The key here is zero, and because we set $length to zero this function will have the effect of inserting the replacement into the string.


2 Answers

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

like image 91
urmaul Avatar answered Sep 18 '22 05:09

urmaul


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

substr on PHP Manual

like image 25
Tim Cooper Avatar answered Sep 18 '22 05:09

Tim Cooper