Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert a string into a string given an index

Tags:

string

php

I know this is a really simple question, but I was just wondering if there is a native php method to inject a string into another string. My usual response to a new text manipulation is to consult the manual's listings of string functions. But I didn't see any native methods for explicitly inserting a string into another string so I figured i'd consult SO.

The answer is likely some kind of combination of the php native string functions OR simply regex (which makes my eye's bleed and my brain melt so I avoid it).

EX: Take a string like some-image.jpg and inject .big before .jpg yielding some-image.big.jpg

like image 765
Derek Adair Avatar asked Sep 13 '10 20:09

Derek Adair


People also ask

How do you add a string to a specific index?

Use the slice() method to insert a string at a specific index of another string, e.g. str. slice(0, index) + 'example' + str. slice(index) . The slice method allows us to get the substrings before and after the specific index and insert another string between them.

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

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

Python add strings with + operator The easiest way of concatenating strings is to use the + or the += operator. The + operator is used both for adding numbers and strings; in programming we say that the operator is overloaded. Two strings are added using the + operator.


1 Answers

You can use substr_replace to insert a string by replacing a zero-length substring with your insertion:

$string = "some-image.jpg";
$insertion = ".big";
$index = 10;

$result = substr_replace($string, $insertion, $index, 0);

From the manual page (the description of the length (4th) argument):

If length is zero then this function will have the effect of inserting replacement into string at the given start offset.

like image 67
Daniel Vandersluis Avatar answered Oct 11 '22 16:10

Daniel Vandersluis