Insert a string into a string given an index
Solution 1
You can do anything with regular expressions!
For your specific request, the solution would be:
$var = 'myimage.jpg';
$new_var = preg_replace('/\.jpg$/', '.big$0', $var);
I would suggest reading up on how to write regular expressions, as they can be very useful in development (here's a starting point).
Solution 2
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.
Solution 3
See this: http://www.krizka.net/2007/12/29/how-to-insert-a-string-into-another-string-in-php/
$newstring=substr_replace($orig_string, $insert_string, $position, 0);
Comments
-
Derek Adair almost 2 years
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
yieldingsome-image.big.jpg
-
Derek Adair over 13 yearslol refer to my eye's bleeding comment. I'm not opposed to using regex, just writing it!!! haha. Although I've come to terms with the fact that I need to buck up and learn it better.
-
Derek Adair over 13 yearsmy eye's hatred for regex aside... this is a superb tutorial on regex - phpfreaks.com/tutorial/regular-expressions-part1---basic-syntax
-
Bruce over 13 years@Derek regular-expressions.info/tutorial.html if you want to learn regex better ;)
-
Andy over 11 yearsMuch better answer IMO. Using a regex for something as simple as this is overkill
-
CptAJ almost 11 yearsThis assumes that we know the index. We probably don't... so yeah, regex
-
Bruce almost 11 yearsThe question stated given an index. :)