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