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.
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.
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.
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.
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.
$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.
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
substr
on PHP Manual
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With