views:

43

answers:

3

Hi,

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

+2  A: 

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);
Tomasz Kowalczyk
if you are satisfied with my answer, please accept ;]
Tomasz Kowalczyk
+1  A: 

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.

Daniel Vandersluis
Gah! Beaten by seconds :(
erisco
+1  A: 

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

Tim Cooper
lol 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
my eye's hatred for regex aside... this is a superb tutorial on regex - http://www.phpfreaks.com/tutorial/regular-expressions-part1---basic-syntax
Derek Adair
@Derek http://www.regular-expressions.info/tutorial.html if you want to learn regex better ;)
Daniel Vandersluis